This is a migrated thread and some comments may be shown as answers.

Delete Rows from Datatable

1 Answer 197 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Agm
Top achievements
Rank 1
Agm asked on 28 Nov 2013, 03:57 PM
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

1 Answer, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 29 Nov 2013, 03:54 AM
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.
Tags
General Discussions
Asked by
Agm
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
Share this question
or