C# 如何将列表绑定到组合框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/600869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:50:22  来源:igfitidea点击:

How to bind a List to a ComboBox?

c#winformsdata-bindingcombobox

提问by Mobin

I want to connect a BindingSourceto a list of class objects and then objects value to a ComboBox.
Can anyone suggest how to do it?

我想将 a 连接BindingSource到类对象列表,然后将对象值连接到 ComboBox。
任何人都可以建议如何做吗?

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }

    public Country()
    {
        Cities = new List<City>();
    }
}

is my class and I want to bind its namefield to a BindingSource which could be then associated with a ComboBox

是我的班级,我想将其name字段绑定到 BindingSource,然后可以将其与 ComboBox 关联

采纳答案by Mitch Wheat

As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a BindingList)

当您指的是组合框时,我假设您不想使用 2 路数据绑定(如果是这样,请查看使用 a BindingList

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }
    public Country(string _name)
    {
        Cities = new List<City>();
        Name = _name;
    }
}





List<Country> countries = new List<Country> { new Country("UK"), 
                                     new Country("Australia"), 
                                     new Country("France") };

var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;

comboBox1.DataSource = bindingSource1.DataSource;

comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";

To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1.SelectedItem;.

为了找到在绑定组合框中选择的国家,你会做这样的事情:Country country = (Country)comboBox1.SelectedItem;

If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the DataSourceimplements IBindingList; one such structure is BindingList<T>.

如果您希望 ComboBox 动态更新,您需要确保您已设置为DataSourceimplements的数据结构IBindingList;一种这样的结构是BindingList<T>.



Tip: make sure that you are binding the DisplayMemberto a Property on the class and not a public field. If you class uses public string Name { get; set; }it will work but if it uses public string Name;it will not be able to access the value and instead will display the object type for each line in the combo box.

提示:确保将 绑定DisplayMember到类上的属性而不是公共字段。如果你的类使用public string Name { get; set; }它会工作,但如果它使用public string Name;它将无法访问该值,而是将显示组合框中每一行的对象类型。

回答by Andrew Hare

Try something like this:

尝试这样的事情:

yourControl.DataSource = countryInstance.Cities;

And if you are using WebForms you will need to add this line:

如果您使用的是 WebForms,则需要添加以下行:

yourControl.DataBind();

回答by Henk Holterman

For a backgrounder, there are 2 ways to use a ComboBox/ListBox

对于后台程序,有两种方法可以使用 ComboBox/ListBox

1) Add Country Objects to the Items property and retrieve a Country as Selecteditem. To use this you should override the ToString of Country.

1) 将 Country 对象添加到 Items 属性并检索 Country 作为 Selecteditem。要使用它,您应该覆盖 Country 的 ToString。

2) Use DataBinding, set the DataSource to a IList (List<>) and use DisplayMember, ValueMember and SelectedValue

2) 使用 DataBinding,将 DataSource 设置为 IList (List<>) 并使用 DisplayMember、ValueMember 和 SelectedValue

For 2) you will need a list of countries first

对于 2) 您首先需要一个国家/地区列表

// not tested, schematic:
List<Country> countries = ...;
...; // fill 

comboBox1.DataSource = countries;
comboBox1.DisplayMember="Name";
comboBox1.ValueMember="Cities";

And then in the SelectionChanged,

然后在 SelectionChanged 中,

if (comboBox1.Selecteditem != null)
{
   comboBox2.DataSource=comboBox1.SelectedValue;

}

回答by Mobin

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }

    public Country()
    {
        Cities = new List<City>();
    }
}

public class City 
{
    public string Name { get; set; } 
}

List<Country> Countries = new List<Country>
{
    new Country
    {
        Name = "Germany",
        Cities =
        {
            new City {Name = "Berlin"},
            new City {Name = "Hamburg"}
        }
    },
    new Country
    {
        Name = "England",
        Cities =
        {
            new City {Name = "London"},
            new City {Name = "Birmingham"}
        }
    }
};
bindingSource1.DataSource = Countries;
member_CountryComboBox.DataSource = bindingSource1.DataSource;
member_CountryComboBox.DisplayMember = "Name";
member_CountryCombo

Box.ValueMember = "Name";

This is the code I am using now.

这是我现在使用的代码。

回答by Robert Tonnessen

public MainWindow(){
    List<person> personList = new List<person>();

    personList.Add(new person { name = "rob", age = 32 } );
    personList.Add(new person { name = "annie", age = 24 } );
    personList.Add(new person { name = "paul", age = 19 } );

    comboBox1.DataSource = personList;
    comboBox1.DisplayMember = "name";

    comboBox1.SelectionChanged += new SelectionChangedEventHandler(comboBox1_SelectionChanged);
}


void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    person selectedPerson = comboBox1.SelectedItem as person;
    messageBox.Show(selectedPerson.name, "caption goes here");
}

boom.

繁荣。

回答by John M

If you are using a ToolStripComboBox there is no DataSource exposed (.NET 4.0):

如果您使用的是 ToolStripComboBox,则不会公开数据源 (.NET 4.0):

List<string> someList = new List<string>();
someList.Add("value");
someList.Add("value");
someList.Add("value");

toolStripComboBox1.Items.AddRange(someList.ToArray());