Search code examples
c#listboxwaf

Create multiple ListBoxes - Windows applications forms


I'm trying to create multiple ListBoxes with different id's.

I want to do something like this:

int count = 0
for(int i = 0; i < 10; i++){
   ListBox count = new ListBox();
   count++;
}

The question is: How to create create multiple ListBoxes?


Solution

  • A Listbox is a control that should be added to the Controls collection of its container. I suppose that this is your form and you will call this code inside some kind of event of your form (like Form_Load for example) or better inside the constructor of the form after the call to InitializeComponents()

    for (int i = 0; i < 10; i++)
    {
        // Create the listbox
        ListBox lb = new ListBox();
    
        // Give it a unique name
        lb.Name = "ListBox" + i.ToString();
    
        // Try to define a position on the form where the listbox will be displayed
        lb.Location = new Point(i * 50,0);
    
        // Try to define a size for the listbox
        lb.Size = new Size(50, 100);
    
        // Add it to the Form controls collection
        // this is the reference to your form where code is executing
        this.Controls.Add(lb);
    }
    
    // Arrange a size of your form to be sure your listboxes are visible
    this.Size = new Size(600, 200);