Chris Ruskai
Chris Ruskai

Reputation: 459

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".

Upvotes: 14

Views: 36404

Answers (3)

Dokman
Dokman

Reputation: 43

If you have an instance from every button you can make with your button or your event to make something like

 CheckBox myCheckedBox = (CheckBox)sender;

Upvotes: 0

Sheela K R
Sheela K R

Reputation: 79

In this case with help of dynamically assign Name property how to achive checkbox.checked property , in some other action like submit button. how can i get all check box is checked and which is created in loop?

Upvotes: 1

spajce
spajce

Reputation: 7092

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);
}

Upvotes: 21

Related Questions