向具有自动增量DataColumn的DataTable添加行值

4
我想在一个DataTable中添加一行,其中包含一个具有自动增量属性的数据列。
DataTable tblproduct = new DataTable();

DataColumn CartItemId = new DataColumn();
CartItemId.ColumnName = "CartItemId";
CartItemId.DataType = System.Type.GetType("System.Int32");
CartItemId.AutoIncrement = true;
CartItemId.AutoIncrementSeed = 1;
CartItemId.AutoIncrementStep = 1;
CartItemId.ReadOnly = true;
CartItemId.Unique = true;

tblproduct.Columns.Add(CartItemId);
tblproduct.Columns.Add("CampaignId", typeof(int));
tblproduct.Columns.Add("SubCatId", typeof(int));
tblproduct.Columns.Add("Size", typeof(string));
tblproduct.Columns.Add("Qty", typeof(int));

tblproduct.Rows.Add(3, 345,"Hello", 1);
tblproduct.Rows.Add(5, 3455,"Hecfghhgdfllo", 8);

我不想在自增列中插入值。它应该是自动生成的值,但上面的代码对我没有用。

1个回答

8

在添加行时,最好尝试以下方法:

        DataRow dr = tblproduct.NewRow();
        dr["CampaignId"] = 3;
        dr["SubCatId"] = 345;
        dr["Size"] = "Hello";
        dr["Qty"] = 1;
        tblproduct.Rows.Add(dr);

来自DataColumn.AutoIncrement属性

您可以使用DataRow类的ItemArray属性并传入一个值数组来创建新行。 这对于自动递增设置为true的列可能存在潜在问题,因为其值是自动生成的。要使用ItemArray属性,请在数组中该列的位置放置null。

将您的代码更改为以下内容:

        tblproduct.Rows.Add(null,3, 345, "Hello", 1);
        tblproduct.Rows.Add(null,5, 3455, "Hecfghhgdfllo", 8); 

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