如何将List绑定到ComboBox?

Mob*_*bin 100 c# data-binding combobox winforms

我想连接一个BindingSource类对象列表,然后将对象值连接到一个ComboBox.
谁能建议怎么做?

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

    public Country()
    {
        Cities = new List<City>();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Mit*_*eat 148

正如你所说的一个组合框,我假设你不想使用双向数据绑定(如果有的话,请看一下使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)



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";
Run Code Online (Sandbox Code Playgroud)

  • 你能解释或添加`bindingSource1`的声明吗? (12认同)
  • `comboBox1.DataSource = bindingSource1.DataSource;` 正确吗?或者应该是“comboBox1.DataSource = bindingSource1;”? (2认同)

Hen*_*man 25

对于背景,有两种方法可以使用ComboBox/ListBox

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

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

对于2),您首先需要一个国家列表

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

comboBox1.DataSource = countries;
comboBox1.DisplayMember="Name";
comboBox1.ValueMember="Cities";
Run Code Online (Sandbox Code Playgroud)

然后在SelectionChanged中,

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

}
Run Code Online (Sandbox Code Playgroud)

  • 感谢但是这里有点问题在运行应用程序时,名称在组合框中不可见 (2认同)

小智 22

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");
}
Run Code Online (Sandbox Code Playgroud)

繁荣.