2

我正在尝试根据我在我的第一个(也包含列)中combobox的选择为我的第二个添加值。comboboxdatagridviewtextbox

这是我的代码:

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

出于某种原因,当我使用断点并单步执行程序时,combobox仅在我第二次尝试打开“项目”时才在第二次添加项目combobox

如果我尝试在不调试的情况下运行程序,则不会显示任何内容。知道我做错了什么吗?

4

1 回答 1

1

如果您在 ComboBox 中使用 SelectedIndexChanged,即使您没有单击 ComboBox,您也可能会遇到触发事件的问题。

当您打开和关闭 Windows 窗体时会发生这种情况。

通过使用SelectionChangeCommitted事件,这是一个更好的选择。

当所选项目发生更改并且该更改显示在 ComboBox 中时,将发生 SelectionChangeCommitted 事件。

通过使用 SelectionChangeCommitted 事件,您无需声明 RemoveHandler 和 AddHandler 语句。


另一种可能:

试试Handles cmb.SelectedIndexChanged

在 VB.NET 中有多种声明事件的方法。通常是使用handles 关键字。

Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object,
            ByVal e As EventArgs) Handles cmb.SelectedIndexChanged
于 2013-02-28T14:53:49.383 回答