C # DataTable delete row
I have a DataTable participantAccounts
that is not connected to any database or something.
How can I remove a line from it?
This does not work:
for (int i = participantAccounts.Rows.Count - 1; i >= 0; i--) {
DataRow dr= participantAccounts.Rows[i];
if (Equals(dr["sellrMembId"].ToString(), itemId))
participantAccounts.Rows.RemoveAt(i);
}
participantAccounts.AcceptChanges();
It acts like everything is fine, but the row stays in the DataTable. I also tried dr.Delete()
it but it doesn't work. When I try participantAccounts.Rows.Remove(dr)
I get an exceptionThe given DataRow is not in the current DataRowCollection.
What am I doing wrong?
source to share
Finally I found a solution. IT had nothing to do with how the lines were deleted.
DataTable dt = participantAccounts;
dt.Rows.Remove(dt.Rows.Find(itemId));
participantAccounts = dt;
the problem was, i think memberAccounts was viewstate (.ASP) and for this reason it was not updated with the direct approach.
Thanks everyone for the help
source to share
You should use Delete
instead RemoveAt
.
So your code might look like this:
for (int i = participantAccounts.Rows.Count - 1; i >= 0; i--)
{
var dr= participantAccounts.Rows[i];
if (object.Equals(dr["sellrMembId"], itemId))
dr.Delete();
}
participantAccounts.AcceptChanges();
Note : your remote DataRows will be represented in the DataTable and have RowStatus = Deleted
until you call the method AcceptChanges
on the DataTable. Once called, the AcceptChanges
deleted DataRows will be removed from the table.
See MSDN for help on the method DataRow.Delete
.
source to share
You should use a foreach loop to get each line and find the specific line you want to delete. Below are the code snippets.
foreach (DataRow row in participantAccounts.Rows)
{
if (row["sellrMembId"].ToString() == itemId)
{
participantAccounts.Rows.Remove(row);
participantAccounts.AcceptChanges();
break;
}
}
source to share