0

I have 5 ComboBoxes and want to populate each of them by the same DataSet

foreach (Control c in panPrev.Controls)
{
    if ((string)c.Tag == "cb") //these are ComboBoxes
    {
        c.DataSource = ds01.Tables[0];
        c.DisplayMember = "cars";
    }
}

Error 1: 'System.Windows.Forms.Control' does not contain a definition for 'DataSource'...
Error 2: 'System.Windows.Forms.Control' does not contain a definition for 'DisplayMember..

Please, help.

4

2 回答 2

4

You have to cast them to ComboBox, anyway, i would use the Enumerable.OfType approach:

var combos = panPrev.Controls.OfType<ComboBox>();
foreach (var combo in combos)
{
    combo.DataSource = ds01.Tables[0];
    combo.DisplayMember = "cars";
}

Enumerable.OfType filters the controls by the type and casts them accordingly.

Note that you need to add using System.Linq;.

于 2012-06-28T10:30:52.900 回答
1

You have to cast it to ComboBox, something like this :

foreach (Control c in panPrev.Controls)
{
    if (c is ComboBox) 
    {
        (c as ComboBox).DataSource = ds01.Tables[0];
        (c as ComboBox).DisplayMember = "cars";
    }
}
于 2012-06-28T10:30:23.170 回答