Reputation: 1124
I have two comboboxes; one contains a list of countries, and the other contains a list of cities. How do I set it so that when you select a country, that country's cities become visible in the other combobox?
I suppose this is basically creating the item collection for the second box based on the selected value of the first one.
EDIT: I'm looking for something like this:
If cboCountry.Text = "Australia" Then
cboCity.Collection("Melbourne, "Sydney")
End If
Upvotes: 0
Views: 3158
Reputation: 546045
Load the data into a Dictionary(Of String, List(Of String))
which contains the mapping from countries to cities.
Then just look the selected country up in the dictionary and iterate over its values.
Here’s an example of how to do the latter part. This assumes that you’ve already loaded your dictionary data (obviously don’t hard-code the values in code):
' As a private Form variable:
Private cities As New Dictionary(Of String, List(Of String))()
' … Load data in Form_Load.
' In the citiesCombo.SelectedValueChanged event of the combo box:
cboCity.Items.Clear()
For Each city As var In cities(cboCountry.Text)
cboCity.Items.Add(city)
Next
If you just want to test this with some toy data, here’s some:
Private cities As New Dictionary(Of String, List(Of String))() From { _
{"England", New List(Of String)() From {"London", "Darthmouth", "Oxford", "Cambridge"}}, _
{"Wales", New List(Of String)() From {"Cardiff", "Swansea"}}, _
{"Scotland", New List(Of String)() From {"Edinburgh", "Glasgow", "Aberdeen"}} _
}
Upvotes: 1
Reputation: 1157
EDIT
Going on your edit, i have changed the code, this should be what you're looking for :)
Put this in to the combo box 1 selected value changed event and should work.
Private Sub cboCountry_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cboCountry.SelectedValueChanged
If cboCountry.Text = "England" Then
cboCity.Items.Add("London")
End If
End Sub
Upvotes: 0