Search code examples
c#datatable

Removing certain row from datatable C#


I am trying to remove rows from datatable in which a certain cell is empty. I have tried using for loop but to no avail.

for (int i = dtbl.Rows.Count - 1; i >= 0; i--)
        {
           DataRow dr = dtbl.Rows[i];
            if (dr["id"] == null)
               dtbl.Rows.Remove(dr);
        }

enter image description here

If the cell of ID column is empty, then that row should be deleted. Any help is appreciated. Thanks in advance.


Solution

  • Change your test to this one.

    for (int i = dtbl.Rows.Count - 1; i >= 0; i--)
    {
        DataRow dr = dtbl.Rows[i];
        if (dr.IsNull("id"))
            dtbl.Rows.Remove(dr);
    }
    

    See docs: DataRow.IsNull

    or you can use a check against the special field DbValue.Null

    if (dr["id"] == DbNull.Value)
    

    Another approach is this one

    for (int i = dtbl.Rows.Count - 1; i >= 0; i--)
    {
        DataRow dr = dtbl.Rows[i];
        if (dr.IsNull("id"))
            dr.Delete();
    }
    dtbl.AcceptChanges();  
    

    this last one just marks the row for deletion, but the row remains in the table until you call AcceptChanges. (So this approach is suitable for a foreach loop)
    Calling DataRow.Delete is the preferred way to work if you plan to update the real database table at later time (for example when you want your user delete many rows from a bound grid and then make a single update to the database only if the user clicks on a Save button).