Reputation: 1432
I'm using WinFroms and trying to reflect control(ComboBox) changes to DataSource using BindingSource. Actualy I want to see what item is selected in comboBox.
My model is:
public class Foo
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
public class Bar
{
public List<Foo> Foos { get; set; }
public Foo SelectedFoo { get; set; }
}
Binding:
List<Foo> lst = new List<Foo>();
lst.Add(new Foo{Name="Name1"});
lst.Add(new Foo{Name="Name2"});
Bar bar = new Bar { Foos = lst };
InitializeComponent();
// bSource - is a BindingSource on the form
this.bSource.DataSource = bar;
// cbBinds - is a ComboBox
this.cbBinds.DataSource = bar.Foos;
this.cbBinds.DataBindings.Add(new Binding("SelectedItem", this.bSource, "Foos", true));
This code works and all Foos are displyed in cbBinding. But I also want to reflect when selected item changed in combobox. So I want Bar.SelectedFoo become equal to cbBinds.SelectedItem(not using change event of comboBox).
I can't figure out how to do this. Is it possible?
Upvotes: 1
Views: 59
Reputation: 125197
The main problem in your code is you set a data-binding to Foos
property of your list while you should setup data-binding to SelectedFoo
.
When you set up data-binding using below codes:
comboBox1.DataSource = List1;
comboBox1.DataBindings.Add(new Binding("SelectedItem", Model1, "Property1", true));
In first line you say the combo box show all items of List1
.
In second line, you say bind SelectedItem
of Combo to Model1.Property1
which means when you change selected item of combo, Model1.Property1
will be set to selected item of combo.
So your code should be like this:
this.comboBox1.DataBindings.Add(new Binding("SelectedItem", bs, "SelectedFoo", true));
Note
Reading above descriptions. now you know using a BindingSource
is not mandatory and you can also write your code this way:
this.comboBox1.DataSource = bar.Foos;
this.comboBox1.DataBindings.Add(new Binding("SelectedItem", bar, "SelectedFoo", true));
Upvotes: 2