我尝试根据我combobox
(包含combobox
列中的第一个datagridview
的选择,为我的第二个textbox
添加值)。
这是我的代码:
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
Try
'Sub Recurrence combobox is selected
If DataGridView1.CurrentCell.ColumnIndex = 4 Then
'Verify what is chosen in the Recurrence textbox
Dim rowIndex = DataGridView1.CurrentCell.RowIndex
Dim FirstComboboxValue = DataGridView1(3, rowIndex).Value
If Not IsNothing(FirstComboboxValue) Then
Dim cmb As ComboBox = TryCast(e.Control, ComboBox)
RemoveHandler cmb.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged)
AddHandler cmb.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged)
End If
End If
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
我的处理程序触发朝向ComboBox_SelectedIndexChanged事件的触发器:
Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
If DataGridView1.CurrentCell.ColumnIndex = 4 Then
Dim comboBox As ComboBox = CType(sender, ComboBox)
Dim cbCell As DataGridViewComboBoxCell = DirectCast(DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(4), DataGridViewComboBoxCell)
Dim rowIndex = DataGridView1.CurrentCell.RowIndex
Dim FirstComboboxValue = DataGridView1(3, rowIndex).Value
'Clear items so they don't keep adding on each other
cbCell.Items.Clear()
Select Case FirstComboboxValue
Case "Choice1"
cbCell.Items.Add("Item1")
cbCell.Items.Add("Item2")
Case "Choice2"
cbCell.Items.Add("Item3")
cbCell.Items.Add("Item4")
Case "Choice3"
cbCell.Items.Add("Item5")
Case "Choice4"
cbCell.Items.Add("Item6")
cbCell.Items.Add("Item7")
End Select
'Remove event handler to prevent memory leak
RemoveHandler comboBox.SelectedIndexChanged, AddressOf ComboBox_SelectedIndexChanged
End If
End Sub
出于某种原因,当我使用断点并逐步执行该程序时,只有在第二次尝试打开"项目&#34时,才会在第二个combobox
中添加这些项目; combobox
。
如果我尝试在没有调试的情况下运行程序,则不显示任何内容。知道我做错了吗?
答案 0 :(得分:1)
如果您在ComboBox中使用SelectedIndexChanged,即使您没有单击ComboBox,也可能遇到触发事件的问题。
当您打开和关闭Windows窗体时会发生这种情况。
使用 SelectionChangeCommitted 事件为此更好。
当所选项目发生更改并且组合框中显示更改时,会发生SelectionChangeCommitted事件。
通过使用SelectionChangeCommitted事件,您无需声明RemoveHandler和AddHandler语句。
另一种可能性:
尝试使用处理cmb.SelectedIndexChanged
有几种方法可以在VB.NET中声明事件。通常使用的是handle关键字。
Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object,
ByVal e As EventArgs) Handles cmb.SelectedIndexChanged