4

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).

Unihedron
  • 10,902
  • 13
  • 62
  • 72
MLavine
  • 195
  • 1
  • 5
  • 13

1 Answers1

13

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();
            }
        }
    }
Sunil
  • 2,885
  • 5
  • 34
  • 41
  • 1
    Yeah, that's what I ended up doing and it worked, it just seemed kinda hacky and I was trying to understand WHY I was still getting deleted rows, as this is the only place anywhere in code I am deleting anything, and I couldn't wrap my head around what was happening. But thank you regardless. – MLavine Apr 17 '13 at 19:30