开发者

c# dynamic checkboxes creating

I am trying to create dynamic checkboxes in a for loop. But I am getting error not during compiling but when I run create checkbox button and run that function. Can you please tell me what I am doing wrong?

 public void CreateCheckBox (int i)
         {
              int y = 10;
              CheckBox[] _cb = new CheckBox[i];
              String chkBox = "chkBox_";
              for (int n = 0; n<i; n++)
                    {
                       _cb[n].Location = new Point(10, y);
     开发者_开发百科                  _cb[n].Name= chkBox + n.ToString();
                       form1.Controls.Add(_cb[n]);
                       y+= 15;
                    }
         }


Inside the loop, you'll have to create a new instance of checkbox.

for (int n = 0; n<i; n++)
{
   _cb[n] = new CheckBox();
   _cb[n].Location = new Point(10, y);
   _cb[n].Name= chkBox + n.ToString();
   form1.Controls.Add(_cb[n]);
   y+= 15;
}


When you define an Array of Checkboxes, the objects inside the array are initialized to null. You need to create an instance of the Checkbox using new Checkbox().

In my opinion, you don't need to save them into a Checkbox[] since the Form manages a control collection. So, this code snippet is maybe more readable:

public void CreateCheckBox (int max)
{
    String name = "chkBox_";
    int y = 10;
    for (int i = 0; n < max; i++)
    {
        Checkbox current = new Checkbox();
        current.Location = new Point(10, y);
        current.Name= name + i.ToString();
        form1.Controls.Add(current);
        y+= 15;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜