C# 将行值添加到具有 AutoIncreamented DataColumn 的 DataTable
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12190487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add Row Values to DataTable Having AutoIncreamented DataColumn
提问by Vedank Kulshrestha
I want to add a row in a DataTable having a Data Column which has an auto Increament Property.
我想在具有自动增量属性的数据列的数据表中添加一行。
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);
I don't want to insert the values in Autoincreamented column. It should be Autogenerated value but above code didn't work for me.
我不想在 Autoincreamented 列中插入值。它应该是自动生成的值,但上面的代码对我不起作用。
采纳答案by Adriaan Stander
When adding the row, rather try something like
添加行时,请尝试类似的操作
DataRow dr = tblproduct.NewRow();
dr["CampaignId"] = 3;
dr["SubCatId"] = 345;
dr["Size"] = "Hello";
dr["Qty"] = 1;
tblproduct.Rows.Add(dr);
also from DataColumn.AutoIncrement Property
也来自DataColumn.AutoIncrement 属性
You can create a new row using the ItemArray property of the DataRow class and passing in an array of values. This is a potential problem for a column with its AutoIncrement set to true, because its value is generated automatically. To use the ItemArray property, place null in the column's position in the array.
您可以使用 DataRow 类的 ItemArray 属性创建一个新行并传入一个值数组。对于 AutoIncrement 设置为 true 的列来说,这是一个潜在的问题,因为它的值是自动生成的。要使用 ItemArray 属性,请将 null 放置在数组中列的位置。
change your code to something like
将您的代码更改为类似
tblproduct.Rows.Add(null,3, 345, "Hello", 1);
tblproduct.Rows.Add(null,5, 3455, "Hecfghhgdfllo", 8);

