Delete Rows from Datatable

2 posts, 0 answers
  1. Agm
    Agm avatar
    26 posts
    Member since:
    Sep 2012

    Posted 28 Nov 2013 Link to this post

    Hi,
    I am having data in Session and casting it to a Datatable.
    and I want to delete some of the rows from that Datatable based on a comparison (please the code below).
    it doesnt give the expected result.
    could you please advise me on this??


               
                DataTable dtchange = (DataTable)Session["Data"];
                DataSet ds = getdata(txt_HideDual.Text.ToString());
                if (dtchange.Rows.Count != 0)
                {
                    for (int i = 0; i < dtchange.Rows.Count; i++)
                    {
                        for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                        {
                            if (dtchange.Rows[i]["Name"].ToString() == ds.Tables[0].Rows[j]["Name"].ToString())
                            {
                                //dtchange.Rows.RemoveAt(i); --- This doesnt work
                                dtchange.Rows[i].Delete();
                                dtchange.AcceptChanges();
                            }
                        }
                    }
                                 Session["Data"] = dtchange;
                }


    Thanking you,


    AGM Raja
  2. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 28 Nov 2013 Link to this post

    Hi Agm,

    Please try the following C# code to delete a data row from DataTable.

    C#:
    if (dtchange.Rows.Count != 0)
    {
        for (int i = 0; i < dtchange.Rows.Count; i++)
        {
            for(int j=0;j<ds.Tables[0].Rows.Count;j++)
                if (dtchange.Rows[i]["Name"].ToString() == ds.Tables[0].Rows[j]["Name"].ToString())
            {
                DataRow dr = dtchange.Rows[i];
                //delete the datarow from the datatable
                dtchange.Rows.Remove(dr);
                    dtchange.AcceptChanges();
            }
        }
                    
    }

    Hope this will helps you.
    Thanks,
    Shinu.
Back to Top