当我拒绝表上的更改时,我遇到了数据表问题。我在下面创建了一个示例来演示该问题:
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 和该表中的 1 行。
我现在删除该行:
row.Delete();
这会将行状态设置为已删除。
在这个阶段,我意识到我犯了一个错误,并想再次添加该行。所以我再次创建新行并将其添加到 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 已删除
添加了 table.Rows[1].RowState
现在,我已经改变了对整个事情的看法,想回到我开始的方式,所以我调用了 RejectChanges:
table.RejectChanges();
当我这样做时,我收到以下错误:
Column 'Name' is constrained to be unique. Value 'Steve' is already present.
我知道有 2 行具有相同的值,但我认为由于 RowStates 不同,因此拒绝更改会导致这一点。
有什么想法可以解决这个问题吗?
在我的实时代码中,我使用它在 2 个网格之间移动行(比如允许用户选择哪些列是可见的)
我在 Visual Studio 2012 中使用 C#4.0
提前致谢