0
votes

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?

2
Does the Binding has an overload to add the initial selected value as parameter?Stefan
@Stefan There is an overload where one can set the nullValue (and which I'm not using):Ivan-Mark Debono
Do you have binding errors in the logs / debugoutput?Fildor
How you added items to the combobox?Fabio
@Fabio By using an IList<Customer> as the datasource. Set once and never change, unless the form is completely cleared.Ivan-Mark Debono

2 Answers

1
votes

This is a typical issue in WinForms bindings. To deal with it you can use the following pattern anywhere when you might need to reset a binding:

private MyObject myObject;

// gets or sets the currently bound object
public MyObject MyObject
{
    get
    {
        return myObject;
    }
    set
    {
        myObject = value;

        myObjectBindingSource.RaiseListChangedEvents = false;
        myObjectBindingSource.EndEdit();

        // rebind
        myObjectBindingSource.DataSource = null;
        myObjectBindingSource.DataSource = myObject;

        myObjectBindingSource.RaiseListChangedEvents = true;
        myObjectBindingSource.ResetBindings(false);
    }
}

And then, instead of

bindingSource.DataSource = myObject = new MyObject();

just set the new property:

MyObject = new MyObject();
0
votes

The problem was the 2 bindings on the control. The binding to the Text property was removed and the combobox now behaves as expected.