N.Pelss
N.Pelss

Reputation: 15

Adding the same items to multiple comboboxes

I have 30 comboboxes and in each one of them I have to add the same items. Is there a faster way to do this than typing the same code all over again for 30 times?

        comboBox1.Items.Add("K");
        comboBox1.Items.Add("H");
        comboBox1.Items.Add("L");
        comboBox1.Items.Add("T");
        comboBox1.SelectedIndex = 0;

        comboBox2.Items.Add("K");
        comboBox2.Items.Add("H");
        comboBox2.Items.Add("L");
        comboBox2.Items.Add("T");
        comboBox2.SelectedIndex = 1;

... and so on..

Upvotes: 1

Views: 1491

Answers (4)

Lamloumi Afif
Lamloumi Afif

Reputation: 9081

You add a method FillCombo

void FillCombo(Control ctrl)
{
    foreach (ComboBox cb in ctrl.Controls) 
    {
     cb.Items.Add("K");
    cb.Items.Add("H");
    cb.Items.Add("L");
    cb.Items.Add("T");
    cb.SelectedIndex = 0;
    }
}

To use it :

FillCombo(this);

Upvotes: 0

Dejan Dular
Dejan Dular

Reputation: 373

InitComboBox(comboBox1);
InitComboBox(comboBox2);
...


private void InitComboBox(ComboBox cb)
{
    cb.Items.Add("K");
    cb.Items.Add("H");
    cb.Items.Add("L");
    cb.Items.Add("T");
    cb.SelectedIndex = 0;
}

Upvotes: 1

TwoRedCells
TwoRedCells

Reputation: 116

string[] values = new[] { "K", "H", "L", "T" };
foreach(string value in values) 
{
    combobox1.Items.Add(value);
    combobox2.Items.Add(value);
}

Even better, if the ItemsCollection has an AddRange method:

string[] values = new[] { "K", "H", "L", "T" };
combobox1.Items.AddRange(values);
combobox2.Items.AddRange(values);

Upvotes: 1

Selman Genç
Selman Genç

Reputation: 101731

You can iterate over all comboboxes using OfType method:

int i = 0;
foreach(var cmbBox in this.Controls.OfType<ComboBox>())
{
    cmbBox.Items.Add("K");
    cmbBox.Items.Add("H");
    cmbBox.Items.Add("L");
    cmbBox.Items.Add("T");
    cmbBox.SelectedIndex = i++;
}

Upvotes: 1

Related Questions