Home > Back-end >  How can I disable a ComboBox item if the selected value is only relevant to a certain option?
How can I disable a ComboBox item if the selected value is only relevant to a certain option?

Time:02-08

I have 4 combo boxes on my windows form.

ComboBox1 has 2 items which are "STUDENT" and "PERSONNEL".

If the user selected "PERSONNEL" on ComboBox1, ComboBox2 to ComboBox4 would be disabled. But if the user changed it to "STUDENT", ComboBox2 to ComboBox4 is enabled again.

I tried an if statement:

If cbSORP.SelectedItem Is "PERSONNEL" Then
        cbCourse.Enabled = False
        cbYear.Enabled = False
        cbSection.Enabled = False
    Else
        cbCourse.Enabled = True
        cbYear.Enabled = True
        cbSection.Enabled = True
    End If

I also tried putting it in a panel and using a timer but still no luck. I'm still learning so please go easy on me.

CodePudding user response:

It's a long time since I programmed in VB, but if I recall correctly, the Is operator tells you whether two variables refer to the exact same object (i.e. they point to the same memory). It does not compare the values of two variables. Change Is to = and it should work fine:

If cbSORP.SelectedItem = "PERSONNEL" Then    ' <-- changed comparison operator
    cbCourse.Enabled = False
    cbYear.Enabled = False
    cbSection.Enabled = False
Else
    cbCourse.Enabled = True
    cbYear.Enabled = True
    cbSection.Enabled = True
End If

See help on Is operator (to see why something that sounds right won't work here) and help on comparison operators for using = and friends in Visual Basic.

Best of luck, and don't give up! Everyone was a learner.

CodePudding user response:

you have to use ComboBox's Text property instead of SelectedItem property in SelectedIndexChanged event of ComboBox,

Private Sub cbSORP_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
   If cbSORP.Text = "PERSONNEL" Then
       cbCourse.Enabled = False
       cbYear.Enabled = False
       cbSection.Enabled = False
   ElseIf cbSORP.Text = "STUDENT" Then
       cbCourse.Enabled = True
       cbYear.Enabled = True
       cbSection.Enabled = True
   End If
End Sub
  •  Tags:  
  • Related