ComboBox DataBinding causes ArgumentException
Solution 1
Bind to "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");
Solution 2
For simple databinding, this will work
cl.Person = new Person{ Name="Harold" };
comboBox.DataBindings.Add("Text",cl.Person, "Name");
But I don't think that's what you want. I think you want to bind to a list of items, then select one. To bind to a list of items and show the Name property, try this:
comboBox.DataSource = new List<Person> {new Person{Name = "1"}, new Person{Name = "2"}};
comboBox.DisplayMember = "Name";
Provided your Person class overrides Equals() such that, say, a Person is equal to another if they have the same Name, then binding to the SelectedItem property will work like so:
Cl cl = new Cl {Person = new Person {Name="2" }};
comboBox.DataBindings.Add("SelectedItem", cl, "Person");
If you can't override Equals(), then you just have to make sure you're referencing a Person instance from the DataSource list, so the code below works for your specific code:
Cl cl = new Cl();
cl.Person = ((List<Person>)comboBox1.DataSource)[1];
comboBox.DataBindings.Add("SelectedItem", cl, "Person");
Solution 3
Try
comboBox.DataBindings.Add("Text", cl, "Person.Name");
instead
You need to tell the combobox which property on it you want to bind to which property on your object (it's Text property, in my example which will show the Name property of the selected person).
*EDIT:* Actually scrap that, I was getting confused. You almost had it, only combobox doesn;t have a property called item, you want SelectedItem instead, like this:
Cl cl = new cl();
comboBox.DataSource = new List<Person> {new Person{Name = "1"}, new Person{Name = "2"}};
comboBox.DataBindings.Add("SelectedItem", cl, "Person");
StuffHappens
Updated on April 22, 2020Comments
-
StuffHappens about 4 years
I several objects of class: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; } }
and a class that has a property of type
Person
:class Cl { public Person Person { get; set; } }
And I want to bind
Cl.Person
to combobox. When I try to do it like this:Cl cl = new cl(); comboBox.DataSource = new List<Person> {new Person{Name = "1"}, new Person{Name = "2"}}; comboBox.DataBindings.Add("Item", cl, "Person");
I get an
ArgumentException
. How should I modify my binding to get the correct program behavior?
Thanks in advance! -
StuffHappens about 13 yearsI want combobox to contain Persons instead of just their names.
-
Iain Ward about 13 years@StuffHappens: Yes they will but ignore that anyway and see my update