The following code works depending when you set the AllowDBNull property: CODEdc = new DataColumn("par_value"); dc.AllowDBNull = false; // Here is the problem dc.DataType = System.Type.GetType("System.String"); dc.Caption = "par_value"; DtParam.Columns.Add(dc); The dc.AllowDBNull = false; will throw an exception if there is an attempt to set this column to null. There are two cases: a) The table has no rows. Maybe some columns and you want to add new column. -Use the above code to add the columns but with AllowDBNull=true (this is the reason the default value in fact is true). -Add row(s) to the table: DataRow dr = DtParam.NewRow();DtParam.Rows.Add(dr); -Now set the AllowDbNull = false; for the columns with not nulls -Set column data. An exception will be thrown if null is assigned to columns with AllowDBNull false. So, you should use try-catch. b) The table already has rows. That means there are columns but you want to add a new column with AllowdBNull = false. -Use above code example to add the columns but with AllowDBNull=false; -Set column data on existing rows or add new rows as explained in a) An exception will be thrown if null is assigned to columns with AllowDBNull false. Example: dtCbx is a DataTable with some columns and rows. CODEDataColumn dc = new DataColumn("par_value"); dc.AllowDBNull = false; dc.DataType = System.Type.GetType("System.String"); dc.Caption = "par_value"; dtCbx.Columns.Add(dc); DataRow dr = dtCbx.NewRow(); dr["par_value"]="Gigi"; dtCbx.Rows.Add(dr); Or CODEDataColumn dc = new DataColumn("par_value"); dc.AllowDBNull = false; dc.DataType = System.Type.GetType("System.String"); dc.Caption = "par_value"; dtCbx.Columns.Add(dc); DataRow dr = dtCbx.NewRow(); dtCbx.Rows.Add(dr); dtCbx.Rows[dtCbx.Rows.Count -1]["par_value"]="Gigi"; An exception is thrown e.g. "Column 'par_value' does not allow nulls" if : dr["par_value"]=null; or dtCbx.Rows[dtCbx.Rows.Count -1]["par_value"]=null; -obislavu- |
|