I类的几个对象:
class Person
{
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
public override string ToString()
{
return Name + "; " + Sex + "; " + Age;
}
}和一个具有Person类型属性的类
class Cl
{
public Person Person { get; set; }
}我想要将Cl.Person绑定到combobox。当我尝试这样做的时候:
Cl cl = new cl();
comboBox.DataSource = new List<Person> {new Person{Name = "1"}, new Person{Name = "2"}};
comboBox.DataBindings.Add("Item", cl, "Person");我得到了一个ArgumentException。我应该如何修改我的绑定来获得正确的程序行为?
提前感谢!
发布于 2011-03-29 20:10:09
绑定到"SelectedItem":
var persons = new List<Person> { new Person() { Name = "John Doe"}, new Person() { Name = "Scott Tiger" }};
comboBox1.DisplayMember = "Name";
comboBox1.DataSource = persons;
comboBox1.DataBindings.Add("SelectedItem", cl, "Person");发布于 2011-03-29 20:05:00
对于简单的数据绑定,这是可行的
cl.Person = new Person{ Name="Harold" };
comboBox.DataBindings.Add("Text",cl.Person, "Name");但我不认为这是你想要的。我认为您想要绑定到一个项目列表,然后选择一个。要绑定到项列表并显示Name属性,请尝试执行以下操作:
comboBox.DataSource = new List<Person> {new Person{Name = "1"}, new Person{Name = "2"}};
comboBox.DisplayMember = "Name";假设您的Person类覆盖了Equals(),例如,如果一个Person与另一个Person同名,则绑定到SelectedItem属性的工作方式如下:
Cl cl = new Cl {Person = new Person {Name="2" }};
comboBox.DataBindings.Add("SelectedItem", cl, "Person");如果您不能重写Equals(),那么您只需确保您引用的是DataSource列表中的Person实例,因此下面的代码适用于您的特定代码:
Cl cl = new Cl();
cl.Person = ((List<Person>)comboBox1.DataSource)[1];
comboBox.DataBindings.Add("SelectedItem", cl, "Person");发布于 2011-03-29 19:57:50
试一试
comboBox.DataBindings.Add("Text", cl, "Person.Name");相反,
您需要告诉combobox您希望将其上的哪个属性绑定到对象上的哪个属性(它是Text属性,在我的示例中,它将显示所选人员的Name属性)。
*EDIT:*实际上放弃了这一点,我有点困惑了。你几乎就做到了,只是combobox没有名为item的属性,你想要的是SelectedItem,如下所示:
Cl cl = new cl();
comboBox.DataSource = new List<Person> {new Person{Name = "1"}, new Person{Name = "2"}};
comboBox.DataBindings.Add("SelectedItem", cl, "Person");https://stackoverflow.com/questions/5472021
复制相似问题