当您在DataGridView
中添加ComboBoxColumn
时,我不知道如何处理ComboBox
的更改事件
'Adding To DGV data on form load
Dim cmbovoce As New DataGridViewComboBoxColumn()
cmbovoce.HeaderText = "Fruit"
cmbovoce.Name = "cmbovoce"
cmbovoce.MaxDropDownItems = 4
cmbovoce.Width = 100
cmbovoce.Items.Add("apple")
cmbovoce.Items.Add("pear")
cmbovoce.Items.Add("cherries")
cmbovoce.Items.Add("plums")
DataGridView1.Columns.Add(cmbovoce)
我强烈建议您使用Cell事件,例如CellValidating
, CellValueChanged
,…检测变化。您试图处理其SelectedIndexChange
事件的组合框是所有单元格的唯一实例。
无论如何,如果你想知道如何处理SelectedIndexChange
事件,你可以这样做:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim c = New DataGridViewComboBoxColumn()
c.HeaderText = "Fruit"
c.Name = "c"
c.MaxDropDownItems = 4
c.Width = 100
c.Items.Add("apple")
c.Items.Add("pear")
c.Items.Add("cherries")
c.Items.Add("plums")
Me.DataGridView1.Columns.Add(c)
For index = 1 To 5
Me.DataGridView1.Rows.Add()
Next
End Sub
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
If (TypeOf (e.Control) Is ComboBox) Then
Dim combo = CType(e.Control, ComboBox)
RemoveHandler combo.SelectedIndexChanged, AddressOf c_SelectedIndexChanged
AddHandler combo.SelectedIndexChanged, AddressOf c_SelectedIndexChanged
End If
End Sub
Private Sub c_SelectedIndexChanged(sender As Object, e As EventArgs)
If (Me.DataGridView1.Columns(Me.DataGridView1.CurrentCell.ColumnIndex).Name = "c") Then
Dim combo = CType(sender, ComboBox)
'Do something with combo
End If
End Sub