C DataTable delete row method analysis

  • 2020-10-31 21:58:13
  • OfStack

This article describes C# DataTable delete line method, to share for your reference. Specific implementation methods are as follows:

Own deletion example (drTemp is the table, gvSummary is gridview of dev. Right-click and click grid delete) :

1, dtTemp. Rows. RemoveAt (gvSummary FocusedRowHandle);

2, dtTemp. Rows [gvSummary FocusedRowHandle]. Delete (); dtTemp.AcceptChanges();

In C#, if you want to delete a line from DataTable, you can do the following:

1. If you just want to delete a row from datatable, you can use delete of DataRow, but you have to let DataTable know after you delete it, so you need the.AcceptChanges () method, because this deletion is only an identification deletion, like the IsDelete field that we usually use in databases.

After Delete(), the datatable.AccepteChanges () method is required to confirm the full deletion, because Delete() simply marks the status of the corresponding column as deleted, and the row can be undeleted by rolling back via ES44en.RejectChanges ().

2. Complete deletion requires Rows.Remove (DataRow dr) method, and also just delete 1 line. If you want to loop delete, please continue reading.

Rows.RemoveAt(int index) method, so if you are a fan of foreach, please change your taste here, and if you are a loyal i++ fans, please change your thinking. Let's first look at the above program written forward (wrong, not available)


for (int i = 0, j = dt.Rows.Count; i < j; i++)
{
  if (Convert.ToInt32(dt.Rows[i]["RowID"]) == RowID)
 dt.Rows.RemoveAt(i);
}

The error is that RemoveAt() of datatable will update index of dataTable after deletion, so the index you want to delete may not be your Convert.es72EN32 (dt.Rows [i]["RowID"]) == index of RowID, or it will throw an exception saying that the index you visited does not exist.

Use datatable.Rows.RemoveAt (i) with caution. To delete multiple lines, use Delete() in succession, and then use AccepteChanges() to confirm the deletion.

Use the select method:

First mark the record to be deleted under 1, and then delete the line of select. The example code is as follows:


for (int i = 0; i < len; i++)
{
  if (((CheckBox)Rp.Items[i].FindControl("CB")).Checked)
  {
 dt.Rows[i]["C0"] = 1;// Marks the record to delete 
  }
}
foreach (DataRow r in dt.Select("c0=1"))
{
  r.Delete();
}
Rp.DataSource = dt;
Rp.DataBind();

If you are interested, you can test run the example of this article to deepen your understanding. I hope this article will be helpful for you to learn C# programming.


Related articles: