从datatable中删除datarow

fla*_*404 6 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)
Run Code Online (Sandbox Code Playgroud)

那你怎么做得对呢?

谢谢.

Cos*_*lis 10

advRow是一个阵列.您必须确定要删除的数组中的哪一行.

dt.Rows.Remove(advRow[0]);
Run Code Online (Sandbox Code Playgroud)

当然,这只会将其从数据表中删除,不一定是它背后的数据源(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();
Run Code Online (Sandbox Code Playgroud)

  • .AcceptChanges()仅适用于表中存在的行!在.Delete()之后,该行仍然存在(作为DataRowState.Deleted)但不在.Remove()之后!所以.AcceptChanges()在这个座位中没有必要. (2认同)