galford13x
galford13x

Reputation: 2541

binding multiple ComboBoxes to 1 List<>

I'm trying to bind multiple ComboBoxes to a single List. However when I select a value in 1 combobox, all ComboBoxes that are binded to List change to the same value.

List<Country> countryList = new List<Country>();
// Add contries to list.  There are two properties string Name, and string Code
comboBox1.DataSource = countryList;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Code";


comboBox2.DataSource = countryList;
comboBox2.DisplayMember = "Name";
comboBox2.ValueMember = "Code";

Now when I select a country from comboBox1, it also select comboBox2. I would prefer not creating a seperate list for each ComboBox.

Upvotes: 4

Views: 2443

Answers (2)

A Reynaldos
A Reynaldos

Reputation: 11

If is only a pair, can be like this:

comboBox1.DataSource = Countries;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Code";

comboBox2.DataSource = Countries;
comboBox2.BindingContext = new BindingContext();
comboBox2.DisplayMember = "Name";
comboBox2.ValueMember = "Code";

If there are more, or in diffrent forms, better create a methode in a public:

public ComboBox bindCombo(ComboBox _cb, DataTable _dt)
{
    _cb.DataSource = _dt;
    _cb.BindingContext = new BindingContext();
    _cb.ValueMember = _dt.Columns[0].ToString();
    _cb.DisplayMember = _dt.Columns[0].ToString();
    return _cb;
}

Upvotes: 1

Conrad Frix
Conrad Frix

Reputation: 52675

Sorry you have to create a new list. If you can you just create another list.

comboBox2.DataSource = countryList.ToList();

However if that doesn't work for you you can create a separate binding Context for one of the combo boxes and do it that way

        BindingContext bcG1 = new BindingContext();

        comboBox1.BindingContext = bcG1;

        comboBox1.DataSource = Countries;
        comboBox1.DisplayMember = "Name";
        comboBox1.ValueMember = "Code";

        comboBox2.DataSource = Countries;
        comboBox2.DisplayMember = "Name";
        comboBox2.ValueMember = "Code";

Upvotes: 4

Related Questions