Remove DataRows From DataTable

Remove DataRows From DataTable

Added by Nasir Mahmood updated on Friday, November 15, 2013

Problem:

Sometimes we want to delete DataRow(s) from DataTable. There are several methods to achieve this task.

Setup:

For this test we have DataTable having two columns (ID,Name) and 10 DataRows having ID from 1 to 9. Now we want delete DataRows having ID = 2,4,5,7,9. Let's try different methods to achieve this task.

private DataTable dataTable = new DataTable();
string IDS = "2,4,5,7,9";
dataTable.Columns.Add(new DataColumn("ID", typeof(string)));
dataTable.Columns.Add(new DataColumn("Name", typeof(string)));            
for (int i = 0; i < 10; i++)
{
    DataRow dr = dataTable.NewRow();
    dr["ID"] = i;
    dr["Name"] = "Name " + i;                
    dataTable.Rows.Add(dr);
}
dataGridView1.DataSource = dataTable;

Using Forward For Loop:

for (int i = 0; i < dataTable.Rows.Count; i++)
{
    if (IDS.Contains(dataTable.Rows[i]["ID"].ToString()))
    {
        dataTable.Rows[i].Delete();
        i = i - 1;
    }
}

In above code we have to re-assign value of "i" so that no item missed for comparison, if we want to compare only one item then we can break loop in “if” condition.

Using Reverse For Loop:

for (int i = dataTable.Rows.Count-1; i!=0; i--)
{
    if (IDS.Contains(dataTable.Rows[i]["ID"].ToString()))
    {
        dataTable.Rows[i].Delete();                    
    }
}

if we want to compare only one item then we can break loop in “if” condition.

Using DataTable.Select:

var rows = dataTable.Select("ID IN(" + IDS + ")");
foreach (var row in rows)
{
    row.Delete();
}

Using DataTable.Select Extension Method:

public static class Extensions
{        
    public static DataTable RemoveRows(this DataTable dataTable, string filter)
    {
        dataTable.Select(filter).RemoveRows();
        return dataTable;
    }
    public static void RemoveRows(this IEnumerable<DataRow> rows)
    {
        foreach (var row in rows)
            row.Delete();
    }
}

and to remove DataRows we can use it as.

dataTable.RemoveRows(" ID IN(" + IDS + ")");

Related Tags

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected