I have DataTable participantAccounts
which is not connected to any database or something.
How can I delete a row from it?
This is not working :
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 row still remains in DataTable.
I also tried dr.Delete()
but that neither works.
When I try participantAccounts.Rows.Remove(dr)
I get an exception The given DataRow is not in the current DataRowCollection.
What I am doing wrong?
if (participantAccounts.Rows.Contains(itemId))
{
DataRow foundRow = participantAccounts.Rows.Find(itemId);
participantAccounts.Rows.Remove(foundRow);
}
for (int i = participantAccounts.Rows.Count - 1; i >= 0; i--)
{
DataRow dr= participantAccounts.Rows[i];
if (Equals(dr["sellrMembId"].ToString(), itemId))
{
participantAccounts.Rows.Delete();
participantAccounts.AcceptChanges();
}
}
Finally I found the solution. IT had nothing to do with way how rows were deleted.
DataTable dt = participantAccounts;
dt.Rows.Remove(dt.Rows.Find(itemId));
participantAccounts = dt;
the problem was, I think, participantAccounts was a viewstate (.ASP) , and it for that reason it was not updated with direct approach.
Thank everyone for help
You should use Delete
instead of RemoveAt
.
So your code could look like:
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 deleted DataRows will present in DataTable and have RowStatus = Deleted
until you will call AcceptChanges
method on DataTable. After calling AcceptChanges
, deleted DataRows will be removed from the table.
See MSDN for reference on DataRow.Delete
method.
This should do the work..
dataSet1.Customers.Rows[0].Delete();
OR
dataSet1.Tables["Customers"].Rows[0].Delete();
How to: Delete Rows in a DataTable
You should use foreach loop to get each row and find particular row which you want to remove. Below is code snippets.
foreach (DataRow row in participantAccounts.Rows)
{
if (row["sellrMembId"].ToString() == itemId)
{
participantAccounts.Rows.Remove(row);
participantAccounts.AcceptChanges();
break;
}
}
int index = -1;
for (int i = participantAccounts.Rows.Count - 1; i >= 0; i--)
{
DataRow dr= participantAccounts.Rows[i];
if (Equals(dr["sellrMembId"].ToString(), itemId))
{
index = i;
break;
}
}
participantAccounts.Rows.RemoveAt(index);
participantAccounts.AcceptChanges();
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