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?
The
FindControlmethod 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 anUpdatePanelthat’s also inside the Page; you need to callFindControlon theUpdatePaneland notPage.FindControlas you are doing.The reason your output says:
checkbox not found checkbox is checkedis because you are callingtest.checkeddirectly, which will always work since that’s the ID you gave to your checkbox.Again,
FindControlis 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.