首页 > 解决方案 > 我如何在 datagridview 中创建组合框的 selected_index_changed 事件

问题描述

我的datagridview名称是“DG”,我添加了以编程方式命名的组合框列,如下面的代码所示。我想创建调用组合框的itemchanged的事件。我使用DG_CellLeave事件,但它不会在项目选择后立即调用,而是在何时调用我们离开单元格。我想创建立即调用组合框的选择更改事件的事件。

    Dim item As New DataGridViewComboBoxColumn
    item.DataSource = dset.Tables("tab")
    item.HeaderText = "item"
    item.Name = "item"
    item.DisplayMember = "p_name"
    item.DataPropertyName = "item"
    DG.Columns.Add(item)

为此我应该选择哪个事件...

标签: vb.net

解决方案


你应该看看:DataGridView.EditingControlShowing Event。每当编辑控件显示在DataGridView. 它可以像下面这样处理/使用:

Dim gridComboBox As ComboBox

Private Sub DG_EditControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs)
    ' Check to see if the ColumnIndex is where we expect to have the DropDown
    If (DG.CurrentCell.ColumnIndex = 1) Then
        ' Get the ComboBox that is being shown
        gridComboBox = TryCast(e.Control, ComboBox)
        If Not (gridComboBox Is Nothing) Then
            ' Always remove the Event Handler before Adding, when setting them at runtime
            RemoveHandler gridComboBox.SelectedIndexChanged, AddressOf gridComboBox_SelectedIndexChanged
            AddHandler gridComboBox.SelectedIndexChanged, AddressOf gridComboBox_SelectedIndexChanged
        End If
    End If
End Sub

Private Sub gridComboBox_SelectedIndexChanged(sender As Object, e As EventArgs)
    Dim dropDown As ComboBox = TryCast(sender, ComboBox)
    if not(dropDown is nothing) then
        Dim drv as DataRowView =  dropDown.SelectedItem
        if Not (drv is nothing) then
           Debug.Print(drv("item"))
        end if
    end if
End Sub

SelectedIndexChanged事件是根据在 DataGridView 之外使用的 ComboBox 引发的。


推荐阅读