简体   繁体   English

C#-comboBox1的数据源取决于comboBox2的值

[英]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: 之后,我按如下所示创建了usa_cities和german_cities的对象:

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. 我想根据comboBox1中选择的值来设置comboBox2.DataSource。 For example - user chooses 'USA' in first combobox - and the second combobox should be filled with usa_cities. 例如,用户在第一个组合框中选择“美国”,第二个组合框应填写usa_cities。 If user chooses 'Germany' - then second combobox should be filled with 'german_cities'. 如果用户选择“德国”,则第二个组合框应填充“ german_cities”。

Could you please advise how can I do it? 您能告诉我该怎么做吗?

Thank you, 谢谢,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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