选择更改了DataGridComboBoxColumn中的事件

Joh*_*ñez 1 vb.net datagridview winforms

我有一个带有DatagridComboBoxColumn的数据网格,我想要Fire Event SelectionChanged当用户选择任何东西从ComboBox,做一些操作,我该怎么做任何建议,谢谢

Jay*_*ggs 14

您可以处理DataGridView的EditingControlShowing事件并将编辑控件转换为正在显示的ComboBox,然后连接其SelectionChangeCommitted事件.使用SelectionChangeCommitted处理程序做你需要做的事情.

有关详细信息,请参阅我链接的MSDN文章中的示例代码.

两个重要说明:

  1. 尽管有MSDN文章的示例代码,但最好使用ComboBox SelectionChangeCommitted事件,如此和链接的MSDN文章的评论中所述.

  2. 如果您DatagridComboBoxColumn的DataGridView中有多个,则可能需要确定哪个触发了您的 EditingControlShowing或ComboBox的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
Run Code Online (Sandbox Code Playgroud)