delete datarow from datatable

flavour404 picture flavour404 · Apr 28, 2011 · Viewed 28.6k times · Source

Lets say I have a datatable dt (it contains advertisers) and I want to remove a row from dt where the advertiserID equals a value, how do I do that?

DataTable dt = new DataTable();
//populate the table
dt = DynamicCache.GetAdvertisers();

//I can select a datarow like this:
DataRow[] advRow = dt.Select("advertiserID = " + AdvID);

//how do you remove it, this get's me an error
dt.Rows.Remove(advRow)

so how do you do it correctly?

Thanks.

Answer

Cos Callis picture Cos Callis · Apr 28, 2011

advRow is an ARRAY. You have to identify which row in the array to delete.

dt.Rows.Remove(advRow[0]);

of course, this only removes it from the datatable, not necessarily the data source behind it (sql, xml, ...). That will require more...

and it would be a good idea to check the array or iterate the array after the select...

var datatable = new DataTable();
            DataRow[] advRow = datatable.Select("id=1");
            datatable.Rows.Remove(advRow[0]);
            //of course if there is nothing in your array this will get you an error..

            foreach (DataRow dr in advRow)
            {
                // this is not a good way either, removing an
                //item while iterating through the collection 
                //can cause problems.
            }

            //the best way is:
            for (int i = advRow.Length - 1; i >= 0; i--)
            {
                datatable.Rows.Remove(advRow[i]);
            }
            //then with a dataset you need to accept changes
            //(depending on your update strategy..)
            datatable.AcceptChanges();