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.
2 Answers
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.
Comments
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;
}
checkbox14. Use a class with multiple properties where one is abool-property. Then initialize it from your database query and put them in aList<ClassName>. Use aGridView,RepeaterorDataListwithTemplateFieldsand put yourCheckBoxthere. Then databind it and put your logic into the appropriate event handler, f.e.RowDataBoundif you use aGridView.