1

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

2 Answers 2

6

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Bala what if I want to delete on of these checkboxes? how can I create a form1.Controls.Remove() thing?
@ValNolav to remove, you can do Control cb = form1.FindControl(controlName); form1.Controls.Remove(cb);
0

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

2 Comments

I need to delete textboxes in a row by clicking checkbox in the same row. How can I do that by clicking a button??
I recommend you to store the row index in the checkbox.Tag, then you listen the CheckedChanged event in the textbox (using += ) and in the Event handler, take the row index from the tag of the sender.

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.