我正在尝试创建具有不同id的多个ListBox。
我想做这样的事情:
int count = 0for(int i = 0; i< 10; i ++){ ListBox count = new ListBox(); 计数++;}……
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);
你已经混合了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... }