I have a form where the controls are bound to a simple DTO through a bindingsource. One particular control is a dropdown list and the binding is:
this.cboCustomer.DataBindings.Add(new Binding("SelectedValue", this.bindingSource, "CustomerId", true, DataSourceUpdateMode.OnPropertyChanged));
this.cboCustomer.DataBindings.Add(new Binding("Text", this.bindingSource, "CustomerName", true, DataSourceUpdateMode.OnPropertyChanged));
It has 2 bindings because I'm updating 2 properties of the object.
I also have an event:
private void cboCustomer_SelectedIndexChanged(object sender, EventArgs e)
{
var customer= cboCustomer.SelectedItem as Customer;
if (customer == null)
return;
myObject.AccountNumber = customer.AccountNumber;
}
I enter all relevant information and save the entity. After saving, I set the bindingsource's datasource to a new instance, ie:
bindingSource.DataSource = myObject = new MyObject();
However, after the first time, when I select an item from the dropdown, the SelectedItem
property is always null, even though there are items in the list.
I have to click on a different control, enter something there, and then the selection in the dropdown appears.
Am I missing something?
Binding
has an overload to add the initial selected value as parameter? – Stefan