不运行代码是从ComboBox中选择的相同项目

时间:2014-11-02 06:04:03

标签: vb.net

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

btnConvert.Enabled = True

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

1 个答案:

答案 0 :(得分:1)

根据您的需要,这里有两种不同的选择。选择你需要的那个。我使用SelectedIndexChanged的{​​{1}}事件来证明这个想法。只要从ComboBox中选择一个项目,此事件就会在其方法内运行代码。 Herehere是有关使用事件的更多信息,如果您不熟悉它们。

选项1

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

if

选项2

如果' 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 中的项目每次都没有相同的顺序,但具有唯一名称,那么您可以将项目文本存储在变量中。然后在ComboBox语句中使用该变量来检查并确保下一个所选项目不相同。

if