c#将行添加到具有自动增量列的数据表中
我有一个数据表,有A,B,C列。我已将A列的“is identity”属性设置为true,但我现在无法向表中添加任何行。
我正在尝试的代码是这样的:
dsA.dtA row = dsA.dtA.NewdtARow(); row.B = 1; row.C = 2; dsA.dtA.Rows.Add(row);
我得到NoNullAllowedException,但我不明白为什么。 A列也是PK。 如果我试图设置row.A = 5(或任何类似的)当我尝试更新数据表时说“当identity_insert设置为off时无法在表中插入标识列的显式值”时会出现错误
我该如何解决这个问题? 这令人沮丧。
试试这个。
DataColumn column = new DataColumn(); column.DataType = System.Type.GetType("System.Int32"); column.AutoIncrement = true; column.AutoIncrementSeed = 1; column.AutoIncrementStep = 1; // Add the column to a new DataTable. DataTable table = new DataTable("table"); table.Columns.Add(column); DataRow oRow = table.NewRow(); table.Rows.Add(oRow);
打开数据集xsd文件的设计器,并在现有列的数据表中设置A列的AutoIncrement,AutoIncrementSeed和AutoIncrementStep属性。
尝试以下两种方法之一:
-
设置字段值:
row.A = null; row.B = 1; row.C = 3;
-
向
DataTable
添加行:dtA.Rows.Add(null,1,2);
它们都是相同的只是尝试其中任何一个,它应该让你去。 还要记住,每当你想在DataTable
中使列自动增加时,你必须在其中插入null。