blah blah blah is here! blah blah » Close

up1down
link

Hi,

I have two listboxes on my form and I want to update listbox2 whenever an iem in listbox1 is clicked. For example,

Listbox1 will have category names like countries; USA, Canada, UK, France and so on. And Listbox 2 will have city names for each country. I started with something like

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if ( (string)listBox1.SelectedItem == "USA" )
{
listBox2.Items = "New York, Houston, Boston";

}
else if ((string)listBox2.SelectedItem == "UK")
{
listBox2.Items = "London, Manchaster";
}


I don't know what to write instead of "listbox2.items". Any ideas?

ademmeda
108

EDIT: listBox2 should be listBox1 in the above code, I mistyped it. "else if ((string)listBox2.SelectedItem == "UK")"

last answered one year ago

1 answers

link

Something like this should work:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex > -1)
{
string[] cities = null;
listBox2.Items.Clear();

switch(listBox1.SelectedItem.ToString())
{
case "USA":
cities = new string[]{"New York", "Houston", "Boston"};
listBox2.Items.AddRange(cities);
return;
case "Canada":
cities = new string[]{"Ottawa", "Montreal", "Toronto"};
listBox2.Items.AddRange(cities);
return;
case "UK":
cities = new string[]{"London", "Manchester", "Birmingham"};
listBox2.Items.AddRange(cities);
return;
}
}
}

ademmeda
108

Well, that did what I needed, thank you very much.

Feedback