0

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?

iYonatan
  • 916
  • 3
  • 10
  • 26

2 Answers2

2

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);
Steve
  • 213,761
  • 22
  • 232
  • 286
1

You've mixed up the int and ListBox types, and as for ID's, Name would be sensible choices:

So how about something like this:

for (int i = 0; i < 10; i++)
    {
        ListBox listBox = new ListBox();
        listBox.Name = i.ToString();
        // do something with this listBox object...

    }
Leigh Shepperson
  • 1,043
  • 5
  • 13
  • I got an error under Uid: 'ListBox' does not contain a definition for 'Uid' and no extension method 'Uid' accepting a first argument of type 'ListBox' could be found (are you missing a using directive or an assembly reference?) – iYonatan Oct 16 '15 at 22:35
  • Sorry, I assumed this was WPF. I've edited the answer for WindowsForms. – Leigh Shepperson Oct 16 '15 at 22:40