2

I am creating a program with a Drop Down-list combo Box which contain the items: a,b,cand d.

What I want to do is, when I select an item in the ComboBox and then click a button, the x variable will change. For example when I select b in the ComboBox, the x value will change to 2.

I need this variable for another function. How can I change the x variable?

Caleb Kleveter
  • 11,170
  • 8
  • 62
  • 92
Yon
  • 35
  • 1
  • 5

3 Answers3

2
If ComboBox1.SelectedItem.ToString = "a" Then
    x = 1
ElseIf ComboBox1.SelectedItem.ToString = "b" Then
    x = 2
ElseIf ComboBox1.SelectedItem.ToString = "c" Then
    x = 3
ElseIf ComboBox1.SelectedItem.ToString = "d" Then
    x = 4
End If

Assuming x is an Integer

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75
BanForFun
  • 752
  • 4
  • 15
  • thank you , currently im using `ComboBox.SelectedIndex` and it solve my problem, what the difference with `ComboBox1.SelectedItem` by the way? – Yon Jul 13 '16 at 14:42
  • @Yon - Selected index gets the position of the selected item. Ex. `0` (First) or `1` (Second) or `2` (Third) e.t.c. Selected item gets the text of the selected item (In your case: `a` or `b` or `c` or `d` e.t.c) – BanForFun Jul 13 '16 at 15:01
  • @Yon - Mark an answer so people know that you solved your problem. – BanForFun Jul 13 '16 at 15:11
2

Or you could use a Select Case statement

Select Case ComboBox1.Text
    Case "a"
        x = 1 
    Case "b"
        x = 2
    Case "c"
        x = 3
    Case "d"
        x = 4
End Select
Cal-cium
  • 654
  • 12
  • 22
0

The best way is to bind a datasource to your combobox. That way if you decide to add a new value later or change how it works, this is all in one place:

    Dim dict As New Dictionary(Of String, Integer)
    dict.Add("a", 1)
    dict.Add("b", 2)
    dict.Add("c", 3)
    dict.Add("d", 4)
    ComboBox1.DisplayMember = "Key"
    ComboBox1.ValueMember = "Value"
    ComboBox1.DataSource = New BindingSource(dict, Nothing)

then in the SelectedValueChanged Event you can read the value of x:

Private Sub ComboBox1_SelectedValueChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedValueChanged
    If ComboBox1.SelectedValue IsNot Nothing Then x = CInt(ComboBox1.SelectedValue)
End Sub
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143