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

时间:2015-10-16 22:24:15

标签: c# listbox waf

我正在尝试使用不同的ID创建多个ListBox。

我想做这样的事情:

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

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

2 个答案:

答案 0 :(得分:2)

Listbox是应该添加到其容器的Controls集合的控件。我想这是你的表单,你会在调用InitializeComponents()

后,在表单的某种事件中调用此代码(例如Form_Load)或更好的在表单的构造函数内部
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);

答案 1 :(得分:1)

你已经混淆了int和ListBox类型,而对于ID&#39; s,Name是明智的选择:

那么这样的事情怎么样:

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

    }