Reputation: 13
I am unable to find the asp:checkbox on my asp web app using the FindControl method. I put a checkbox on my form using:
<asp:CheckBox ID="test" Text="Test checkbox" runat="server" />
In my codebehind I have the following:
Control checkbox = FindControl("test");
if (checkbox != null) Debug.Print("checkbox found");
else Debug.Print("checkbox not found");
if (test.Checked) Debug.Print("checkbox is checked");
else Debug.Print("checkbox is unchecked");
however my output (with the checkbox checked) is: checkbox not found checkbox is checked
Can somebody please tell me what I am doing wrong?
Upvotes: 0
Views: 2486
Reputation: 16310
You can use recursive method to find the control in following way:
private Control RecursiveFindControl(Control root, string id)
{
if (root.ID == id) return root;
foreach (Control c in root.Controls)
{
Control t = RecursiveFindControl(c, id);
if (t != null) return t;
}
return null;
}
Use above recursive method to find the control:
CheckBox checkbox = RecursiveFindControl(Page, "test") as CheckBox;
if (checkbox != null) Debug.Print("checkbox found");
else Debug.Print("checkbox not found");
if (test.Checked) Debug.Print("checkbox is checked");
else Debug.Print("checkbox is unchecked");
Upvotes: 0
Reputation: 63956
The FindControl
method is not recursive and will only find your control if you call it on the immediate parent of the checkbox. So for example, if the checkbox is placed inside an UpdatePanel
that's also inside the Page; you need to call FindControl
on the UpdatePanel
and not Page.FindControl
as you are doing.
The reason your output says: checkbox not found checkbox is checked
is because you are calling test.checked
directly, which will always work since that's the ID you gave to your checkbox.
Again, FindControl
is not recursive and I am positive that's why it's failing. You can write your own "RecursiveFindControl" method but that's almost always an overkill and inefficient as hell.
Upvotes: 4