Reputation: 2765
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?
Upvotes: 2
Views: 4554
Reputation: 17194
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();
}
Upvotes: 1
Reputation: 6444
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);
}
Upvotes: 2
Reputation: 6490
Try using the following code,
var rows = dataTable.Select("condition to select");
rows.ForEach((r) => r.Delete(););
dataTable.AcceptChanges();
Upvotes: 1
Reputation: 4192
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
Upvotes: 0