2

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Ganeshja
  • 2,675
  • 12
  • 36
  • 57
  • 1
    Update your old question instead of asking a new one - http://stackoverflow.com/questions/15247850/how-to-delete-a-particular-value-from-a-datatable-in-c-sharp/15248019?noredirect=1#comment21503697_15248019 – LukeHennerley Mar 06 '13 at 13:50

4 Answers4

2

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);
}
LukeHennerley
  • 6,344
  • 1
  • 32
  • 50
1

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();
}
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
1

Try using the following code,

  var rows = dataTable.Select("condition to select");
    rows.ForEach((r) => r.Delete(););
    dataTable.AcceptChanges();
Rajesh Subramanian
  • 6,400
  • 5
  • 29
  • 42
0
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

Community
  • 1
  • 1
jordanhill123
  • 4,142
  • 2
  • 31
  • 40