cruskai239 cruskai239 - 23 days ago 19
C# Question

Dynamically Adding Checkboxes to a Windows Form Only Shows one Checkbox

I'm sorry if this seems n00bish, but I have been searching for this for a few days now. I am attempting to dynamically add checkboxes to a windows form; however, only one checkbox appears on the form. Here is my code:

for (int i = 0; i < 10; i++)
{
box = new CheckBox();
box.Tag = i.ToString();
box.Text = "a";
box.AutoSize = true;
box.Location = new Point(10, i + 10);
Main.Controls.Add(box);
}


As you can see I am adding the checkboxes via a for loop. I have tried messing with the location and enabling autosize in case they were somehow overlapping. The result is a single checkbox with text "a".

Answer

Actually you already created a CheckBox but within the same point.

CheckBox box;
for (int i = 0; i < 10; i++)
{
    box = new CheckBox();
    box.Tag = i.ToString();
    box.Text = "a";
    box.AutoSize = true;
    box.Location = new Point(10, i * 50); //vertical
    //box.Location = new Point(i * 50, 10); //horizontal
    this.Controls.Add(box);
}
Comments