0

For example, I have 3 checkbox with ID checkbox1, checkbox2, checkbox3. I need to do a looping in code behind and disable them base on my sql queue result. But if i have more than 10 checkbox I cannot just do it one by one and there are many logics to check. How can I do it? Thanks.

3
  • First you say you have three checkboxes then you say you have more than 10. Not really clear. Commented Apr 29, 2016 at 10:33
  • @TimSchmelter, first is example to print less names, and then comes the real OP's use case with 10+. Sounds clear enough Commented Apr 29, 2016 at 10:34
  • You should not add logic to your control-ids. A name is just a name and should be more meaningful than checkbox14. Use a class with multiple properties where one is a bool-property. Then initialize it from your database query and put them in a List<ClassName>. Use a GridView, Repeater or DataList with TemplateFields and put your CheckBox there. Then databind it and put your logic into the appropriate event handler, f.e. RowDataBound if you use a GridView. Commented Apr 29, 2016 at 10:36

2 Answers 2

1

A common approach would be to declare an array and put all of your controls in there:

Checkbox[] checkboxes = new Checkbox[]{CheckboxOne, CheckboxTwo, AnotherCheckbox};

You can loop through that easily. Note that this allows arbitrary names for controls.

Another approach, which applies only when your control IDs literally follow the pattern ControlNameX, is to use FindControl.

for (int i=1; i<=3; i++)
{
    Checkbox c = ParentControl.FindControl("Checkbox" + i) as Checkbox;
}

Also note that FindControl has to be called on an immediate parent, which means all of controls you are looping through have to be inside one common parent control.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use Control.FindControl to get the control with their ids within the container. If you have checkboxes on form you can use this.FindControl.

int numberofControls=4;
for(int i=1; i < numberofControls; i++)
    ((CheckBox)parentControlId.FindControl("checkbox" + i)).Enabled = false;

If there is any chance that you wont have the control you are looking for then better to check if you got the control.

for(int i=1; i < numberofControls; i++)
{
     CheckBox checkbox = ParentControl.FindControl("checkbox" + i) as Checkbox;
     if(checkbox != null)
           checkbox.Enabled = false;
}

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.