简体   繁体   中英

How to delete a row from a datatable?

How to delete a row from a datatable_ Consider I have 12 rows in my data table, I need to delete one of them using particular row value ..

datatable :

Field Name | Field Type 
------------------------
FirstName  |  Text box
           |
LastName   |  Text box

I need to delete the selected row form the table itself using below code snippet I can retrieve FirstName

string value = (string)selectedRows[i].Cells[0].Value;
Console.WriteLine(outdex);

But how delete it from the data table

Can any one help me out please?

From the OP other question, he wants to get a selected row from a DataGridView and remove this row from a temporary DataTable .

//Get the row that is selected
DataGridViewRow dr = selectedRows.Cast<DataGridViewRow>().FirstOrDefault();
//Your temp DataTable
DataTable dtTemp = new DataTable();
//If there is a row selected
if (dr != null)
{
  var rowToRemove = dtTemp.Rows.Cast<DataRow>().FirstOrDefault(row => row[0] == dr.Cells[0].Value);
  if (rowToRemove != null)
    dtTemp.Rows.Remove(rowToRemove);
}

Here you go:

dt.Rows.Cast<DataRow>()
       .Where(r => r.ItemArray[0] == "Any_Value")
       .ToList()
       .ForEach(r => r.Delete());

OR

DataView view = new DataView(dt);
view.RowFilter = "Column_name = 10";

foreach (DataRowView row in view)
{
  row.Delete();
}

Try using the following code,

  var rows = dataTable.Select("condition to select");
    rows.ForEach((r) => r.Delete(););
    dataTable.AcceptChanges();
if (value == "some deleteValue")
    selectedRows[i].Delete();

If doing this in a loop though, you'd want something more like this answer though: Deleting specific rows from DataTable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM