从datatable中删除datarow

时间:2011-04-27 22:34:34

标签: c# datatable datarow

假设我有一个数据表dt(它包含广告商),我想从dt中删除一行,其中advertiserID等于一个值,我该怎么做?

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)

那你怎么做得对呢?

感谢。

1 个答案:

答案 0 :(得分:10)

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();