简体   繁体   English

C#向具有自动递增列的数据表添加行

[英]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. 我有一个数据表,其中包含A,B,C列。我已将A列的“ isidentity”属性设置为true,但是现在无法向该表添加任何行。

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. 我收到了NoNullAllowedException,但我不明白为什么。 Column A is PK as well. 列A也为PK。 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" 如果我尝试设置row.A = 5(或其他类似值),当我尝试更新数据表时会提示“当identity_insert设置为off时无法为表中的身份列插入显式值”时,我将收到一条错误消息。

How can I solve this issue? 我该如何解决这个问题? It's frustrating. 真令人沮丧

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);

Try one of the these two: 尝试以下两种方法之一:

  1. Set field values: 设置字段值:

     row.A = null; row.B = 1; row.C = 3; 
  2. Add row to DataTable : 将行添加到DataTable

     dtA.Rows.Add(null,1,2); 

They are both the same just try any of them and it should get you going. 他们都是一样的,只要尝试其中的任何一个,它都可以带您去。 Also remember that whenever you want to make a column auto-increment in DataTable then you have to insert null into it. 还请记住,每当要在DataTable中使列自动递增时,都必须在其中插入null。

打开数据集xsd文件的设计器,并在数据表中为现有列设置列A的AutoIncrement,AutoIncrementSeed和AutoIncrementStep属性。

The way that I do it is 我这样做的方式是

public void AppendtodtA(int num1, doubledouble1, string string1)
{
    object[] RowArray = new object[] {null,(int)num1, (double) doubledouble1, (string) string1}
    DataRow CurrentRow = dtA.NewRow();
    CurrentRow.ItemArray = RowArray;
    dtA.Rows.Add(CurrentRow);
}

use ItemArray property and leave a null in the place of the autoincremented column 使用ItemArray属性并在autoincremented列的位置保留null

AppendtodtA(MyNumber,MyDouble,MyString);

Then just call the method with your variables. 然后只需使用变量调用该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM