创建多个 ListBoxes - Windows 应用程序表单

Create multiple ListBoxes - Windows applications forms

我正在尝试创建多个具有不同 ID 的列表框。

我想做这样的事情:

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

问题是:如何创建创建多个ListBox?

您混淆了 int 和 ListBox 类型,至于 ID,Name 是明智的选择:

那么这样的事情怎么样:

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

    }

Listbox 是一个控件,应该添加到其容器的 Controls 集合中。我想这是您的表单,您将在表单的某种事件中调用此代码(例如 Form_Load),或者在调用 InitializeComponents()[=11= 之后更好地在表单的构造函数中调用此代码]

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