0

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;
            }
        }
    }
stuartd
  • 70,509
  • 14
  • 132
  • 163
YArt
  • 19
  • 1
  • 7

1 Answers1

3

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; it sets the RowState to Deleted, but the row remains in the collection until you call AcceptChanges (see the documentation for 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:

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.

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
Jeff Ogata
  • 56,645
  • 19
  • 114
  • 127