Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete datarow from datatable

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.

like image 739
flavour404 Avatar asked Apr 27 '11 22:04

flavour404


People also ask

How do I delete DataRow?

There are two methods you can use to delete a DataRow object from a DataTable object: the Remove method of the DataRowCollection object, and the Delete method of the DataRow object. Whereas the Remove method deletes a DataRow from the DataRowCollection, the Delete method only marks the row for deletion.

How do I delete a row in a data table in Excel?

Delete a row or column Select a row or column that you want to delete. Press Backspace, or select the Table Tools Layout tab >Delete, and then select an option. Note: In Excel, select a row or column that you want to delete, right-click and select Delete , and choose the option you want.


1 Answers

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();
like image 200
Cos Callis Avatar answered Sep 30 '22 15:09

Cos Callis