2011-04-27 74 views
4

假設我有一個數據表dt(它包含廣告客戶),我想從dt中刪除一行,其中advertiserID等於一個值,我該怎麼做?從數據表中刪除datarow

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) 

那麼你如何正確地做到這一點?

謝謝。

+0

你說讓你一個錯誤。什麼錯誤?它說什麼? – 2011-04-27 22:36:20

回答

8

advRow是ARRAY。您必須確定要刪除的數組中的哪一行。

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

啊,那正是我錯過的那條信息 - 非常感謝。你需要做dt.acceptchanges後? – flavour404 2011-04-27 22:47:48

+0

@ flavour404,根據你的更新策略,是的...在某些時候你需要做一個'.AcceptChanges();'(參見我添加的擴展示例...) – 2011-04-27 22:51:24

+0

謝謝Cos,那真是太棒了。 – flavour404 2011-05-03 19:03:20