Reputation: 57
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.
Upvotes: 0
Views: 744
Reputation: 148180
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;
}
Upvotes: 1
Reputation: 56716
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.
Upvotes: 1