2012-03-31 29 views

回答

12

您可以處理DataGridView的EditingControlShowing事件,並將編輯控件強制轉換爲正在顯示的組合框,然後連接其SelectionChangeCommitted事件。使用SelectionChangeCommitted處理程序,你需要做什麼。

請參閱MSDN文章我聯繫瞭解詳細信息中的示例代碼。

兩個重要注意事項:

  1. 儘管MSDN本文的示例代碼,最好使用 組合框SelectionChangeCommitted事件,所討論的here和鏈接的MSDN文章的 意見。

  2. 如果你有一個以上的DatagridComboBoxColumn在 DataGridView中,你可能要確定哪些解僱或者您的 EditingControlShowing或組合框的SelectionChangeCommitted 事件。您可以通過檢查您的DGV CurrentCell.ColumnIndex屬性值來執行此操作。

我修改了MSDN示例代碼位,以顯示我的意思:

Private Sub DataGridView1_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing 
    ' Only for a DatagridComboBoxColumn at ColumnIndex 1. 
    If DataGridView1.CurrentCell.ColumnIndex = 1 Then 
     Dim combo As ComboBox = CType(e.Control, ComboBox) 
     If (combo IsNot Nothing) Then 
      ' Remove an existing event-handler, if present, to avoid 
      ' adding multiple handlers when the editing control is reused. 
      RemoveHandler combo.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectionChangeCommitted) 

      ' Add the event handler. 
      AddHandler combo.SelectionChangeCommitted, New EventHandler(AddressOf ComboBox_SelectionChangeCommitted) 
     End If 
    End If 
End Sub 

Private Sub ComboBox_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) 
    Dim combo As ComboBox = CType(sender, ComboBox) 
    Console.WriteLine("Row: {0}, Value: {1}", DataGridView1.CurrentCell.RowIndex, combo.SelectedItem) 
End Sub 
+0

我早就在等待一個解決方案,以及,謝謝你完美的作品! – 2012-04-02 16:06:59

+0

綜合答案。大拇指和比分! – 2016-01-10 11:24:10