C#中添加一行数据表有一个自动递增列 [英] c# adding row to datatable which has an auto increment column

查看:1344
本文介绍了C#中添加一行数据表有一个自动递增列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据表中,列A,B,C。我已经设置A列的是一种身份属性设置为true,但我不能任何行现在添加到表中。

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.

我想的代码是这样的:

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

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

dsA.dtA.Rows.Add(row);



我越来越NoNullAllowedException,但我不明白为什么。 A列的PK也是如此。如果我试图设置row.A = 5(或任何similiar)当我尝试当IDENTITY_INSERT设置为OFF无法插入的标识列的显式值来更新数据表说我会得到一个错误

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.

推荐答案

试试这个。

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

这篇关于C#中添加一行数据表有一个自动递增列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆