拒绝DataTable上的更改时出现唯一约束错误

时间:2013-06-28 10:21:08

标签: c#-4.0 datatable datarow

当我拒绝对表格进行更改时,我遇到了数据表问题。我在下面创建了一个示例来说明问题:

DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Last_Name", typeof(string));
table.Columns.Add("Male", typeof(Boolean));

foreach (DataColumn column in table.Columns)
{
    if (column.ColumnName == "Name")
    {
        column.Unique = true;
    }
}

DataRow row;

row = table.NewRow();
row["Name"] = String.Format("Steve");
row["Last_Name"] = String.Format("Smith");
row["Male"] = true;

table.Rows.Add(row);

table.AcceptChanges();

所以在这个阶段,我有一个DataTable,它有一个唯一的列约束,在该表中有一行。

我现在删除该行:

row.Delete();

这会将rowstate设置为Deleted。

在这个阶段,我意识到我犯了一个错误,并希望再次添加该行。所以我再次创建新行并将其添加到DataTable:

row = table.NewRow();
row["Name"] = String.Format("Steve");
row["Last_Name"] = String.Format("Smith");
row["Male"] = true;

table.Rows.Add(row);

在此阶段,我的DataTable内容处于以下状态:

table.Rows [0] .RowState is Deleted

table.Rows [1] .RowState已添加

现在,我已经改变了对整个事情的想法,并想回到我的开始,所以我打电话给RejectChanges:

table.RejectChanges();

当我这样做时,我收到以下错误:

Column 'Name' is constrained to be unique.  Value 'Steve' is already present.

我知道有2行具有相同的值,但我认为拒绝更改会因为RowStates不同而加入。

我有什么想法可以解决这个问题吗?

在我的实时代码中,我使用它来在两个网格之间移动行(例如允许用户选择哪些列可见)

我在Visual Studio 2012中使用C#4.0

提前致谢

0 个答案:

没有答案