Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# adding row to datatable which has an auto increment column

I've a datatable, with column A, B, C. I've set column A's "is identity" property to true, but I can't add any row to the table now.

The code I'm trying is this:

dsA.dtA row = dsA.dtA.NewdtARow();

row.B = 1;
row.C = 2;

dsA.dtA.Rows.Add(row);

I'm getting NoNullAllowedException, but I don't understand why. Column A is PK as well. If I tried to set row.A = 5 (or any similiar) I'll get an error when I try to update the datatable saying "cannot insert explicit value for identity column in table when identity_insert is set to off"

How can I solve this issue? It's frustrating.

like image 293
John Smith Avatar asked May 01 '14 14:05

John Smith


2 Answers

Do this way. Reference link

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);
like image 168
Raju Padhara Avatar answered Sep 17 '22 16:09

Raju Padhara


Open the designer of the dataset xsd file and set the AutoIncrement, AutoIncrementSeed and AutoIncrementStep property of the column A in datatable for an existing column.

like image 38
Gary Avatar answered Sep 20 '22 16:09

Gary