Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Deleted row information cannot be accessed through the row" trying to remove unused rows from my datatable

I'm grabbing data, sticking it into a DataTable, and displaying it in a DataGridView bound to that table. Im trying to make it so that data in the datatable that is not included in the current grab is deleted. I'm doing it as follows:

public void FillTable(DataTable table, IEnumerable<MyObject> readings)
{
    var currentReadingsNames = new List<string>();
    var lastParent = string.Empty;
    var index = 0;

    foreach (var reading in readings)
    {
        if (reading.ParentName != lastParent)
        {
            lastParent = reading.ParentName;
            index = 0;
        }
        LoadRow(table, reading, index++);
        currentReadingsNames.Add(MakeKey(reading));
    }

    //Iterate through the rows in our data table. If the row is not one we just loaded, get rid of it.
    foreach (DataRow row in table.Rows)
    {
        if (!currentReadingsNames.Contains(MakeKey(row["ParentID"].ToString(), row["ID"].ToString())))
        {
            row.Delete();
        }
    }
    table.EndLoadData();
}

MakeKey(reading) and MakeKey(properties) returns a string I can use to identify my object two different ways. Assume that this works.

When I run this, I get:

Deleted row information cannot be accessed through the row.

I feel like I shouldn't be attempted to access a deleted row, because I only delete the row after I'm done looking at its values (the parentID and ID column). Does this behave differently than I am understanding? Any ideas why this is happening? If this code should work, maybe the error is somewhere else, but I haven't changed anything else so I would be surprised (I'm trying to add this deleting behavior).

like image 578
MLavine Avatar asked Dec 12 '22 15:12

MLavine


1 Answers

Just add a filter for deleted rows as:

foreach (DataRow row in table.Rows)
{
    if(row.RowState != DataRowState.Deleted) 
    {     
       if (!currentReadingsNames.Contains(MakeKey(row["ParentID"].ToString(), row["ID"].ToString())))
            {
                row.Delete();
            }
        }
    }
like image 77
Sunil Avatar answered Mar 02 '23 00:03

Sunil