且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

DataGridComboBoxColumn中的选择更改事件

更新时间:2023-12-04 14:15:16

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

You can handle your DataGridView's EditingControlShowing event and cast the editing control to the ComboBox being displayed and then wire up its SelectionChangeCommitted event. Use the SelectionChangeCommitted handler do you what you need to do.

请参阅我链接的MSDN文章中的示例代码。

See the sample code in the MSDN article I linked for details.

两个重要说明:


  1. 尽管有MSDN文章的示例代码,***使用
    ComboBox SelectionChangeCommitted 事件,如所讨论的此处以及链接的MSDN文章的
    评论。

  1. Despite the MSDN article's sample code it's best to use the ComboBox SelectionChangeCommitted event, as discussed here and in the comments of the linked MSDN article.

如果您的
DataGridView中有多个 DatagridComboBoxColumn ,则可能要确定哪个触发了
EditingControlShowing 或ComboBox的 SelectionChangeCommitted
事件。您可以通过检查DGV
CurrentCell.ColumnIndex 属性值来实现。

If you have more than one DatagridComboBoxColumn in your DataGridView you might want to determine which fired either your EditingControlShowing or the ComboBox's SelectionChangeCommitted event. You can do this by checking your DGV CurrentCell.ColumnIndex property value.

我稍微修改了MSDN示例代码以显示我的意思:

I reworked the MSDN sample code a bit to show what I mean:

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