【问题标题】:C# - DataSource of comboBox1 depended on comboBox2 valueC# - comboBox1 的数据源依赖于 comboBox2 的值
【发布时间】:2020-01-13 05:15:19
【问题描述】:

我创建了两个类,如下所示:

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;
}

之后,我创建了 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") };

然后我创建了一个对象“国家”,如下所示:

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

在我的应用程序中,我有两个组合框。 第一个组合框允许用户选择一个国家如下:

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

我想根据在comboBox1 中选择的值来设置comboBox2.DataSource。 例如 - 用户在第一个组合框中选择“美国” - 第二个组合框应填充 usa_cities。 如果用户选择“Germany” - 那么第二个组合框应该填充“german_cities”。

您能告诉我该怎么做吗?

谢谢,

【问题讨论】:

标签: c# arrays winforms combobox


【解决方案1】:

您应该为ComboBox1.SelectedIndexChanged 事件添加一个事件处理程序,然后根据ComboBox1.SelectedIndex 的情况使用它来更改ComboBox2 的ItemsSource

【讨论】:

    猜你喜欢
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多