我如何在datagridview中创建组合框的selected_index_changed事件

时间:2019-03-09 16:49:44

标签: vb.net

我的datagridview名称是“ DG”,我添加了以组合方式命名的item的组合框列,如下代码所示。我想创建一个调用combobox的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)

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

1 个答案:

答案 0 :(得分:0)

您应该看一下: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

根据DataGridView外部使用的ComboBox引发SelectedIndexChanged事件。