2012-03-31 28 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