2012-12-25 90 views
6

我有一個WPF DataGrid theDataGrid綁定到包含表的DataSet ds。我想讓用戶首先在網格中選擇它們,然後按下一個按鈕(定位在數據網格之外的某處)來刪除線條。我終於來到了下面的代碼線,做我想做的,但我認爲比較難看:刪除WPF數據網格中的行

DataSet ds = new DataSet(); 
     ... 
    // fill ds somehow 
     ... 
    private void ButtonClickHandler(object Sender, RoutedEventArgs e) 
    { 
     List<DataRow> theRows = new List<DataRow>(); 
     for (int i = 0; i < theDataGrid.SelectedItems.Count; ++i) 
     { 
      // o is only introduced to be able to inspect it during debugging 
      Object o = theDataGrid.SelectedItems[i]; 
      if (o != CollectionView.NewItemPlaceholder) 
      { 
       DataRowView r = (DataRowView)o; 
       theRows.Add(r.Row); 
      } 
     } 
     foreach(DataRow r in theRows) 
     {     
      int k = ds.Tables["producer"].Rows.IndexOf(r); 
      // don't remove() but delete() cause of update later on 
      ds.Tables[0].Rows[k].Delete(); 
     } 
    } 

有沒有更好的方式來做到這一點?例如。一個只需要一個循環,而不必顯式地檢查NewItemPlaceHolder,或者可能有一種更有效的方式來訪問要刪除的行?

(我已經想通了,我不能刪除從第一循環的DS東西,從此theDataGrid.SelectedItems.Count改變每次執行循環...)

+0

我有一個解決方案,你想我添加它? – gasroot

回答

0

我認爲它的工作原理是隻有一個循環:

int count=theDataGrid.SelectedItems.Count; 
int removedCount=0; 
while (removedCount < count) 
{ 
    try{ 
     Object o = theDataGrid.SelectedItems[0]; 
    } 
    catch{ break;} 

    if (o == CollectionView.NewItemPlaceholder) 
    continue; 

    DataRowView r = (DataRowView)o; 
    r.Row.Delete(); 
    removedCount++; 
} 
+0

嗯,謝謝,但沒有。實際上,在「編輯」之後添加的foreach循環是我的第一個「解決方案」。它導致一個未處理的異常。這就是我在問題的最後一行中提到的那個,括號中的那個。 SelectedItems集合在循環過程中發生變化,而foreach計數器引用無效的東西(我認爲)。我期望與第一種方法相同。 – Thomas

+0

@Thomas對於第二個問題你是對的,但至少我確定'Collection Modified Exception'不會被拋出第一個。 – Ramin

+0

由於您增加的索引最終變得比(當前)SelectedItems.Count大,因此它崩潰。如果您每次都檢索SelectedIndex [0],它可能會工作。但是,說實話,手動更新的計數器並不比我的代碼更好。我想要的是像你的第二個建議,但不會崩潰的一個班輪;-) – Thomas

0

您可以向後遍歷去除雙循環:

private void ButtonClickHandler(object Sender, RoutedEventArgs e) { 
    for (int i = theDataGrid.SelectedItems.Count-1; i>=0; --i) 
     if (theDataGrid.SelectedItems[i] != CollectionView.NewItemPlaceholder) 
      ds.Tables[0].Rows[i].Delete(); 
    } 
1

爲了消除按鈕選擇行點擊你可以試試:

private void ButtonClickHandler(object sender, RoutedEventArgs e)//Remove row selected 
    { 
     DataRowView dataRow = (DataRowView)dataGridCodes.SelectedItem; //dataRow holds the selection 
     dataRow.Delete();      
    }