tags:

views:

49

answers:

2

This seems like a simple task but there may be an easier way.

I have a form with 30 comboboxes that all need the same data set. Currently I bind each one:

DataTable t = GetData();

this.ComboBox1.DataSource = t;
this.ComboBox1.DisplayMember = "heading";

this.ComboBox2.DataSource = t;
this.ComboBox2.DisplayMember = "heading";

this.ComboBox3.DataSource = t;
this.ComboBox3.DisplayMember = "heading";

...
...

this.ComboBoxN.DataSource = t;
this.ComboBoxN.DisplayMember = "heading";

Is there a way to bind them all in a less tedius fashion?

Thanks.

+2  A: 
foreach (var control in this.Controls)
{
    if (control is (ComboBox))
    {
        ((ComboBox)control).DataSource = t;
        ((ComboBox)control).DisplayMember = "heading";
    }
}
McKay
Sounds good ... unless not all of the combo boxes are to be bound to the same set (i.e., if there are 33 comboboxes, and 3 of them aren't bound to the same control). In that case, I'd wrap the 30 which are bound to the same source in a container of some sort, e.g., a FlowLayoutPanel or some other panel-type control.
David T. Macknet
Great exactly what I needed thanks.
Steve
@Steve If this is what you're looking for, you should mark the answer as accepted with the check mark.
McKay
As soon as I can. It says I have to wait 4 minutes.
Steve
@Steve Ah. Thanks.
McKay
A: 
private void bindIt(ComboBox c)
{
    c.DataSource = t;
    c.DisplayMember = "heading";
}

private void bindThemAll()
{
    bindIt(this.ComboBox1);
    bindIt(this.ComboBox2);
    bindIt(this.ComboBox3);
    ...
    bindIt(this.ComboBoxN);
}

That way, you're not running the risk of binding any control which isn't supposed to be bound. Yes, lots of repetition, but ....

David T. Macknet