Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One DataSource for multiple controls

I have two ListBox in my winforms application, I assigne a datasource for both of them as follow:

private void MakeMeasurementUnits()
{
    var units = new List<MeasurementUnit>
                    {
                        new MeasurementUnit {Name = "Current", SiUnit = "A"},
                        new MeasurementUnit {Name = "Voltage", SiUnit = "V"},
                        new MeasurementUnit {Name = "Time", SiUnit = "s"},
                        new MeasurementUnit {Name = "Temprature", SiUnit = "°C"}
                    };

    lbxXunit.DataSource = units;
    lbxYunit.DataSource = units;
}

The strange thing is (or maybe because it is my first time!!), in the form when I click on items of one of these lisboxes, the same item in the second listbox gets selected as well. Is this a default behaviour? how to prevent this? If this is default behaviour, what is useful about it?

I found the quick remedy to be making two different datasources (same thing with another name)

like image 240
Saeid Yazdani Avatar asked Jan 03 '12 13:01

Saeid Yazdani


4 Answers

The listbox seems to cache the binding source. This is default behavior. If you want to avoid this, the easy way is to create a copy of the list to bind to the second data source:

lbxXunit.DataSource = units;
lbxYunit.DataSource = units.ToList();

This is useful when you have multiple views of the same data and want to synchronize the selection of these items.

like image 119
Bas Avatar answered Nov 15 '22 00:11

Bas


Yes, this is normal behaviour. It happens because the ListView control uses a BindingSource object to track the currently selected item. (A List has no way to track a selected item without a BindingSource.)

By default, a DataSource in a WinForms control uses a BindingSource created for it by the WinForms system itself.

You can read more about the BindingSource at: http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx

There is an article here which might help too: http://blogs.msdn.com/b/bethmassi/archive/2007/09/19/binding-multiple-comboboxes-to-the-same-datasource.aspx

like image 23
Richard Avatar answered Nov 14 '22 23:11

Richard


The behavior you have noted is the default/correct behavior for winforms controls. You can achieve what you are after by setting a new BindingContext for your second listbox control without creating a copy of your data source.

BindingContext

like image 33
Bueller Avatar answered Nov 14 '22 23:11

Bueller


This is correct behaviour. The datasource management in WindowsForms keeps track of the selected item on control and manipulates binded data too.

The resolution you've found already: is assign 2 different data sources objects to these controls.

like image 44
Tigran Avatar answered Nov 15 '22 00:11

Tigran