选择选定索引时启用/禁用组合框

时间:2017-12-07 21:17:11

标签: vb.net

我尝试在选择特定国家/地区时启用comboxbox,否则应禁用。

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    cboCountry.Items.AddRange(File.ReadAllLines("..\..\TextFiles\countries.txt"))
    cboCounty.Items.AddRange(File.ReadAllLines("..\..\TextFiles\county.txt"))

End Sub

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
    If cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then

        cboCounty.Enabled = True

    Else
        cboCounty.Enabled = False

    End If
End Sub

当我选择任何国家/地区,包括"爱尔兰"组合框被禁用

3 个答案:

答案 0 :(得分:0)

也许试试

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
    If not cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then

        cboCounty.Enabled = True

    Else
        cboCounty.Enabled = False

    End If
End Sub

因为在我看来你的if语句是向后的,每当它被改为爱尔兰以外的东西你写它的方式就会禁用它,因为它在else语句中设置了所以如果你只是反转它,那么它应该工作正常。

答案 1 :(得分:0)

If cboCountry.Text = "Ireland" Then
   cboCounty.Enabled = True
Else
   cboCounty.Enabled = False
End If

因为您在选择爱尔兰时希望这种情况发生,您应该能够检查文本是否设置为爱尔兰

区分大小写适用于此处,因此请确保爱尔兰确实在您正在检查或强制进行比较时显示。

答案 2 :(得分:0)

我真的试过你发布的完全相同的代码,它对我有用。我创建了一个带有两个组合框的Windows窗体,将其名称更改为cboCountry和cboCounty,将其 dropdownstyle 更改为DropDownList,并禁用了cboCounty。

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
   If cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then
      cboCounty.Enabled = True
   Else
      cboCounty.Enabled = False
   End If
End Sub

我也尝试过@Charles May的解决方案,但也很有用。