假设我有一个数据表dt(它包含广告客户),我想从dt中删除一行,其中广告客户id等于一个值,我该怎么做?
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)
那你怎么做才对呢?
谢谢。
最佳答案
advrow是一个数组。必须标识数组中要删除的行。
dt.Rows.Remove(advRow[0]);
当然,这只会从数据表中删除它,不一定是它后面的数据源(sql、xml,…)。这需要更多…
最好检查数组,或者在选择之后迭代数组…
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();