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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With