Deleting a row completely from a dataset

41,613

Solution 1

Try calling

ds.AcceptChanges() 

after row.Delete().

Solution 2

If you want to remove a single data row, RemoveAt is the easier option:

ds.Tables[0].Rows.RemoveAt(rowIndex);

Oscar's answer is also correct, according to the remarks for RemoveAt on MSDN:

When a row is removed, all data in that row is lost. You can also call the Delete method of the DataRow class to just mark a row for removal. Calling RemoveAt is the same as calling Delete and then calling AcceptChanges.

Share:
41,613
CodeNinja
Author by

CodeNinja

Updated on February 16, 2020

Comments

  • CodeNinja
    CodeNinja over 4 years

    I have a remove button on my gridview. On Clicking the remove button , the row should be completely removed from the session. I am currently doing the following :

    protected void gvMainLog_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Remove")
            {
    
                GridViewRow rowSelect = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
                int rowindex = rowSelect.RowIndex;
    
                DataSet ds =  ((DataSet)Session["old"]);
    
                ds.Tables[0].Rows[rowindex].Delete();
    
                Session["old"] = ds;
    
                gvMainLog.DataSource = Session["old"];
                gvMainLog.DataBind();
    
            }
    

    The problem is that :

    ds.Tables[0].Rows[rowindex].Delete();
    

    removes only the content in that row. When I look at the dataset , it shows an empty row.

    Is there a way I can remove the entire row, without it showing an empty row ?

  • Krondorian
    Krondorian over 8 years
    For me it was .RemoveAt(rowIndex) and not .Remove
  • User
    User over 8 years
    @Krondorian Thanks for pointing this out. I've edited my answer accordingly. Both Remove and RemoveAt behave identicially; the only difference between the methods is the parameter you have to pass to identify the row being removed.