开发者

Using programatically created CheckBoxes in Windows Form [C#]

开发者 https://www.devze.com 2023-02-24 09:24 出处:网络
For e开发者_JAVA百科xample, I would like an array of checkboxes: CheckBox[] faults = new CheckBox[20];

For e开发者_JAVA百科xample, I would like an array of checkboxes:

        CheckBox[] faults = new CheckBox[20];

Now how do I place these in my Form and link them to their array name?

Thanks.


How about that:

YourForm.Controls.AddRange(faults);


You have iterate through each checkboxes in faults, but keep in mind they do not overlap so, you can do like this.

Example:

int top = 0;  //used for proper positioning of controls
foreach (CheckBox cb in faults) 
{

   cb.Location =new Point(0 , top); // fixing cb for distinct position
   top +=10; 

   this.Controls.Add(cb);

}


foreach (CheckBox cb in faults) YourForm.Controls.Add(cb);


Assuming you are using MS Visual Studio: create a small test project, add a checkbox to a form named MyForm using the Visual Studio designer and have a look into the generated method InitializeComponent in the file MyForm.designer.cs. This will help you to find out which properties of your checkboxes you will have to initialize. And, of course, you will see where Visual Studio places the call this.Controls.Add(cb).


Try this:

var faults = new CheckBox[20];

Point startPoint = new Point(20, 10);

for (int i = 0; i < faults.Length; i++)
{
    Controls.Add(new CheckBox()
    {
        Location = new Point(startPoint.X, 20 * i + startPoint.Y),
        Text = (i + 1).ToString()
    });
}

Good luck!

0

精彩评论

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

关注公众号