Vb.net 如果从组合框中选择了同一项,则不运行代码

Vb.net 如果从组合框中选择了同一项,则不运行代码,vb.net,Vb.net,所以,我得到了一个组合框,当你从中选择一个项目时,它会启用几个按钮 btnConvert.Enabled = True 基本上,如果用户打开组合框并选择相同的项,我不希望代码运行。我试着调暗一个新的布尔值和所有这些,试图使这成为可能,但它没有得到很好的结果。如果进行了相同的选择,是否有一种简单的方法来阻止该代码?根据您的需要,这里有两种不同的选项。挑一个你需要的。我使用组合框的SelectedIndexChanged事件来演示这个想法。每当从组合框中选择项时,此事件都会在其方法内运行代码。如果

所以,我得到了一个组合框,当你从中选择一个项目时,它会启用几个按钮

btnConvert.Enabled = True

基本上,如果用户打开组合框并选择相同的项,我不希望代码运行。我试着调暗一个新的布尔值和所有这些,试图使这成为可能,但它没有得到很好的结果。如果进行了相同的选择,是否有一种简单的方法来阻止该代码?

根据您的需要,这里有两种不同的选项。挑一个你需要的。我使用组合框的SelectedIndexChanged事件来演示这个想法。每当从组合框中选择项时,此事件都会在其方法内运行代码。如果您不熟悉事件,还可以查看有关使用事件的更多信息

选择1

如果组合框中的项目始终处于相同的顺序,则可以将所选项目索引存储在变量中。然后在if语句中使用该变量来检查并确保下一个选定项不相同

' The variable we'll use to store the most recent selected index
Private _selectedItem As Integer = -1 

' The method set up to be run when an item in ComboBox1 is selected
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    ' Get the combobox that triggered this event (ie: ComboBox1)
    Dim comboBox As ComboBox = CType(sender, ComboBox)

    ' Get the index of the selected item
    Dim selectedIndex As Integer = comboBox.SelectedIndex

    ' Check that the selected index > -1 and that it is also not the same as the last one
    If selectedIndex > -1 AndAlso selectedIndex <> _selectedItem Then
        ' Update the variable with the most recent selected index
        _selectedItem = selectedIndex

        ' Enable/disable the buttons
        Button1.Enabled = False
        Button2.Enabled = True
        Button3.Enabled = True
    End If
End Sub
' The variable we'll use to store the most recent selected text
Private _selectedItem As String

' The method set up to be run when an item in ComboBox1 is selected
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    ' Get the combobox that triggered this event (ie: ComboBox1)
    Dim comboBox As ComboBox = CType(sender, ComboBox)

    ' Get the index of the selected item
    Dim selectedIndex As Integer = comboBox.SelectedIndex

    ' Get the text for that item
    Dim itemName As String = comboBox.Items(selectedIndex)

    ' Check that the selected index > -1 and that the text is also not the same as the last one
    If selectedIndex > -1 AndAlso Not itemName.Equals(_selectedItem) Then
        ' Update the variable with the most recent selected text
        _selectedItem = itemName

        ' Enable/disable the buttons
        Button1.Enabled = False
        Button2.Enabled = True
        Button3.Enabled = True
    End If
End Sub

在类成员中保留上一个组合框选择。与当前选择进行比较。如果它们相等,就不要运行代码。是的,我知道,但是怎么做?嗯,这不是我想要的,这是非常混乱的代码。我的代码也有一些错误。很抱歉,您理解我的答案有困难。我编辑了它,在我的代码中加入了更多的解释和注释,希望能够澄清。你犯了什么错误?请记住,您需要更改我的组合框和按钮的变量名称以匹配您的。哇,谢谢您的时间,现在我了解了一切。我欠你一个人情杰里米谢谢