简体   繁体   中英

C# - DataSource of comboBox1 depended on comboBox2 value

I have created two classes as per below:

class City
{
public string CityName { get; set; }
public string Region { get; set; }

public City(string sCountryName, string sLanguage)
{
    this.CityName = sCountryName;
    this.Region = sLanguage;
}
public override string ToString()
{
    return CityName;
}

class Country
{
public string CountryName { get; set; }
public City[] cities;

public Country(string sCountryName, City[] sCities)
{
    this.CountryName = sCountryName;
    this.cities = sCities;
}

After that I have created objects of usa_cities and german_cities as per below:

City[] usa_cities = new City[] {new City("Washington", "English"),
                        new City("New York", "English"),
                        new City("San Francisco", "English") };

City[] german_cities = new City[] {new City("Berlin", "German"),
                        new City("Hamburg", "German"),
                        new City("Frankfurt", "German") };

And then I have created an object 'countries' as per below:

Country[] countries = new Country[] {new Country("USA", usa_cities),
                                    new Country("Germany", german_cities) };

In my application I have two comboboxes. The first combobox allows user to choose a country as per below:

        comboBox1.DataSource = countries;
        comboBox1.DisplayMember = "CountryName";
        comboBox1.ValueMember = "CountryName";
        comboBox1.SelectedItem = -1;

I would like to set comboBox2.DataSource depending on the value choosen in comboBox1. For example - user chooses 'USA' in first combobox - and the second combobox should be filled with usa_cities. If user chooses 'Germany' - then second combobox should be filled with 'german_cities'.

Could you please advise how can I do it?

Thank you,

您应该添加的事件处理程序ComboBox1.SelectedIndexChanged事件,你再使用更改ItemsSource根据的情况下ComboBox2的ComboBox1.SelectedIndex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM