Yon
Yon

Reputation: 35

Combo Box Drop down list to change a variable

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?

Upvotes: 2

Views: 712

Answers (3)

Matt Wilko
Matt Wilko

Reputation: 27342

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

Upvotes: 0

Cal-cium
Cal-cium

Reputation: 654

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

Upvotes: 2

BanForFun
BanForFun

Reputation: 752

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

Upvotes: 2

Related Questions