0

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?

heatStroke
  • 13
  • 3

2 Answers2

4

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.

Icarus
  • 63,293
  • 14
  • 100
  • 115
0

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");
Akash KC
  • 16,057
  • 6
  • 39
  • 59
  • Precisely what I think is a bad approach and you suggested it! LOL The moment one starts using this method in a control really deep in the control tree you end up with a page slow as a turtle. I had to profile a page using this technique once, and the amount of calls to the recursive function sometimes surpassed the thousands. More than 70% of the time was spent only trying to find a control that could be found in one or 2 function calls at the most. – Icarus Jul 19 '12 at 17:16
  • @Icarus : I am not suggesting OP to use abvoe recursive method but just giving him a alternative to find the control through recursion.... – Akash KC Jul 19 '12 at 17:25
  • @LolCoder: thanks for the help, I am sure this will come in handy in the future! – heatStroke Jul 19 '12 at 18:28