1

I am dynamically generating Checkboxes on button click which I am adding to a panel in TableLayoutPanel.

Panel panel1=new panel();
CheckBox box = new CheckBox();
box.Name = "cb_" + count;
box.AutoSize = true;
panel1.Controls.Add(box);
tableLayoutPanel1.Controls.Add(panel1);
count++;

I need to check if these checkboxes are checked on Save button click. But when i try to retrieve the Checkbox it returns null. (But if I add the checkbox directly to the form instead of TablelayoutPanel I am able to retrieve it.)

for (int i = 0; i >= count; i++)
{
    CheckBox cb =  this.Controls["cb_" + i] as CheckBox;// Returns Null
    if (cb.Checked)
    {
       //Add code
    }
}

How can I get the checbox state?

1
  • It is because this.Controls["cb_" + i] returns null or is not of type CheckBox. Commented Mar 2, 2016 at 9:35

2 Answers 2

1

You are looking in the form controls and not in the tableLayoutPanel1

change the code like this

for (int i = 0; i >= count; i++)
{
    CheckBox cb =  tableLayoutPanel1.Controls["cb_" + i] as CheckBox;
    if (cb.Checked)
        {
           //Add code
        }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Change your loop to this:

foreach(Control c in panel1.Controls)
{
     CheckBox cb = c as CheckBox;
     if (cb!=null)
     {
          if (cb.Checked)
          {
               //Add code
          }
     }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.