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

9

我有一个数据表,包含A、B、C三列。我将A列的“自增”属性设置为true,但现在无法向表中添加任何行。

我尝试的代码如下:

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

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

dsA.dtA.Rows.Add(row);

我遇到了NoNullAllowedException错误,但我不知道为什么。A列也是主键。如果我尝试设置row.A = 5(或任何类似值),然后尝试更新datatable时会出现错误,说“不能在关闭identity_insert的情况下为表中的identity列插入显式值”。
我该如何解决这个问题?这很令人沮丧。

我已经回答过了,但如果您能在dts.rows.add(row)这一行上设置一个断点并检查row.A中携带的内容,那就太好了。 - khalid khan
你可能需要检查你的表的IDENTITY_INSERT是否为开启或关闭状态。 - TaW
ColumnModel.IsIdentity(EF)和DataColumn.AutoIncrement(ADO Datatable)是两个不同框架中的两个不同概念。IsIdentity表示数据库将提供该值。AutoIncrement表示数据表对象将提供该值。 - ileff
4个回答

11

按照以下方式操作。参考链接

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

@John 也可以查看这个帮助文档 - Raju Padhara
9
如果我已经有了一个带有自动增量列的数据表,我只想向该表添加一行,怎么办? - John Smith

2
尝试以下两种方法之一:
  1. Set field values:

    row.A = null;
    row.B = 1;
    row.C = 3;
    
  2. Add row to DataTable:

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

它们都是相同的,只需尝试其中任何一个,它应该可以帮助您。还要记住,每当您想要使DataTable中的列自动递增时,您必须将null插入其中。


两种方法都失败了。第一种甚至无法编译,显示不能将 null 转换为 int。第二种与我的方法一样,只是简单地失败并出现了 NoNullAllowedException。 - John Smith
DataTable dt = new DataTable(); dt.Columns.Add("A", System.Type.GetType("System.Int32")).AutoIncrement = true; dt.Columns.Add("B"); dt.Rows.Add(null, "abc"); dt.Rows.Add(null, "xyz"); 我已经检查过了,在Visual Studio中可以正常运行。 - khalid khan

2

打开数据集 xsd 文件的设计器,并为现有列中的列 A 设置自动递增、自动递增种子和自动递增步骤属性。


0
我做的方式是
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);
}

使用ItemArray属性,在自增列的位置留下一个null

AppendtodtA(MyNumber,MyDouble,MyString);

然后只需使用您的变量调用该方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接