ComboBox DataBinding causes ArgumentException
class Person
{
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
public override string ToString开发者_StackOverflow社区()
{
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?
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");
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");
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");
if you are using Enums may be u have a class of enums you can a combo box like this
Specify the combo box datasourse eg
comboBoxname.DataSource = Enum.GetValues(typeof(your enum));
Now lets bind the combox box since we have the data source
comboBoxname.DataBindings.Add("SelectedItem", object, "field of type enum in the object");
精彩评论