2012-07-25 69 views
-3

我试图在alist中为每个字符串添加一个新的复选框。添加新的复选框

的代码是:

void MainFormLoad(object sender, EventArgs e) 
     { 
      ArrayList alist = new ArrayList(); 
      alist.Add("First"); 
      alist.Add("Second"); 

      foreach (String s in alist) { 

// add new checkbox with different name for each string in alist 

      } 

     } 

请帮助

+0

此问题没有足够的细节可以回答。我假设这是WinForms?请确认。此外,如果你还没有这样做,请阅读http://www.stackoverflow.com/faq – FishBasketGordo 2012-07-25 13:18:37

回答

2
ArrayList alist = new ArrayList(); 
     alist.Add("First"); 
     alist.Add("Second"); 

     int loopCount=1; 
     foreach (String s in alist) 
     { 

      // add new checkbox with different name for each string in alist 
      CheckBox c = new CheckBox(); 
      c.Name = s; 
      c.Text = s; 
      c.Parent = this; 
      c.Visible = true; 

      //position the checkbox 
      c.Top = loopCount*c.Height; 

      this.Controls.Add(c); 
      loopCount++; 


     } 

希望帮助。

+0

我不介意被标记下来,但我想知道为什么。 – RedEyedMonster 2012-07-25 13:32:56

+0

+1来补偿。 – NominSim 2012-07-25 13:36:32

+0

非常感谢:) – RedEyedMonster 2012-07-25 13:39:00

1

这至少应该让你开始:

foreach (String s in alist) 
{    
    CheckBox cb = new CheckBox(); 
    cb.Text = s; 
    this.Controls.Add(cb); 
} 
+0

我用它只增加了第一个不是其他的 – 2012-07-25 13:23:34

+0

你会想在每次迭代期间改变位置以及,否则它们会出现在彼此之上。 (正如我刚才说的,只是为了让你开始)。 – NominSim 2012-07-25 13:25:21

0

创建CheckBox类的一个对象,并设置Name属性值和添加它到Controls集合的任何Container元素。您需要将每个新创建的复选框的位置设置为不同,否则它将全部坐在一个位置(一个位于另一个位置上),并且您将无法看到全部。

int top = 10; 
foreach (String s in alist) 
{ 
    top = top + 10; 
    var chk = new CheckBox(); 
    chk.Name = s; 
    chk.Top=top; 
    groupBox1.Controls.Add(chk); 

} 

我在这里加入新创建的复选框的GroupBox控制与名groupBox1。

1

您可以使用表格的Controls集合动态添加控件。 i用于确保复选框的位置不会过度重叠。

int i = 0; 
foreach (String s in alist) 
{ 
    CheckBox myCheckBox = new CheckBox(); 
    myCheckBox.Name = s; 
    myCheckBox.Text = s; 
    myCheckBox.Size = new Size(74, 13); 
    myCheckBox.Location = new Point(138, i); 
    this.Controls.Add(myCheckBox); 
    i = i + 18; 
} 
+0

名称不一样吗? – 2012-07-25 13:26:44

+0

发布后我更正了。 – 2012-07-25 13:27:35

+0

谢谢贾斯汀..一半的文字被切断,但是 – 2012-07-25 13:34:45