简体   繁体   中英

How to populate more than one controls via DataSet?

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.

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; .

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";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM