简体   繁体   English

不能从数据集中删除两次

[英]can't delete twice from a dataset

First time when i delete from data set all good but second time it gave me this error Deleted row information cannot be accessed through the row. 我第一次从数据集中删除时一切都很好,但是第二次它给了我这个错误无法通过行访问已删除的行信息。

 private void button9_Click(object sender, EventArgs e)
    {
        foreach (DataRow row in ds.Tables["emp"].Rows)
        {
            if (row[0].ToString() == textBox6.Text)
            {
                row.Delete();
                break;
            }
        }
    }

Normally deleting from a collection while enumerating will throw an exception: 通常在枚举时从集合中删除将引发异常:

Collection was modified; enumeration operation might not execute.

In this case, if the data rows haven't just been added, calling DataRow.Delete() doesn't remove the row; 在这种情况下,如果还没有添加数据行,则调用DataRow.Delete()不会删除该行; it sets the RowState to Deleted , but the row remains in the collection until you call AcceptChanges (see the documentation for DataRow.Delete() ). 它将RowState设置为Deleted ,但是该行将保留在集合中,直到您调用AcceptChanges (请参阅DataRow.Delete()的文档)。

So the row is still in the DataTable and the second time you enumerate the collection, the code tries to access the field value and you get the exception: 因此,该行仍在DataTable ,并且第二次枚举集合时,代码将尝试访问字段值,并且您会收到异常:

DeletedRowInaccessibleException: Deleted row information cannot be accessed through the row.

To avoid this error, you can either call AcceptChanges to commit the deletion or check the RowState as mentioned in the answer linked to by @Grant Winney. 为了避免此错误,您可以调用AcceptChanges进行删除,也可以按照@Grant Winney链接的答案中的说明检查RowState

To see an example of this, you can run this code: 要查看此示例,可以运行以下代码:

var table = new DataTable();
table.Columns.Add("Name", typeof(string));

table.Rows.Add("foo");
table.Rows.Add("bar");

table.AcceptChanges();

foreach(DataRow row in table.Rows)
{
    if ((string)row["Name"] == "foo")
    {
        row.Delete();
    }
}

Console.WriteLine(table.Rows[0].RowState);  // Deleted
Console.WriteLine(table.Rows.Count);        // 2
table.Rows[0].AcceptChanges();
Console.WriteLine(table.Rows.Count);        // 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM