Search code examples
c#loopscomboboxfill

How to fill 56 comboBox with loop or something


I have 56 comboBox in my program and I need to fill all of them with the same information. The fastes way that I found is creating a private function for fill the comboBox. And I put 56 times the same function.

But my question is... I can do a loop for fill this 56 comboBox?


Solution

  • Assuming this question is about Windows Forms. The best way to do it is probably to have the similar naming convention for all ComboBox controls you're willing to fill with the same data. Fill them with items within for-loop, adding different suffix to the control you want to find before adding data.

    // Lets say you have 56 ComboBox controls with names like : cbMyComboBox_1, cbMyComboBox_2, ..., cbMyComboBox_56
    for (int i = 1; i <= 56; i++)
    {
        ComboBox comboBox = (ComboBox)this.Controls.Find
            (string.Format("cbMyComboBox_{0}", i), true)[0];
        ComboBoxFill(comboBox);
    }
    
    private void ComboBoxFill(ComboBox comboBox)
    {
        // Fill that ComboBox with data here
    }