开发者

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?

DataTa开发者_如何学Cble 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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜