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).
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With