ComboBox DataBinding导致ArgumentException

时间:2011-03-29 11:49:43

标签: c# winforms data-binding combobox


我有几个类的对象:

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绑定到组合框。当我尝试这样做时:

Cl cl = new cl();
comboBox.DataSource = new List<Person> {new Person{Name = "1"}, new Person{Name = "2"}};
comboBox.DataBindings.Add("Item", cl, "Person");

我得到ArgumentException。我应该如何修改我的绑定以获得正确的程序行为?
提前谢谢!

4 个答案:

答案 0 :(得分:7)

绑定到“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");

答案 1 :(得分:3)

对于简单的数据绑定,这将起作用

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具有相同的Name,那么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");

答案 2 :(得分:1)

尝试

comboBox.DataBindings.Add("Text", cl, "Person.Name");

代替

你需要告诉组合框你要将哪个属性绑定到对象上的哪个属性(它的Text属性,在我的示例中将显示所选人员的Name属性)。

* 编辑: * 其实废话,我感到困惑。你几乎拥有它,只有组合框没有;有一个名为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");

答案 3 :(得分:0)

如果您使用Enums,可能是您有一类枚举,您可以使用这样的组合框

  1. 指定组合框数据,例如

    comboBoxname.DataSource = Enum.GetValues(typeof(your enum));
    
  2. 现在让我们绑定combox框,因为我们有数据源

    comboBoxname.DataBindings.Add("SelectedItem",
                                  object,
                                  "field of type enum in the object");
    
相关问题