1

I'm trying to set two variables to two respective controls, and my current code isn't working. What is the correct syntax?

ascx code:

<ul>
    <li runat="server" id="searchListItem">
       <a href="javascript:void(0)">Search Keywords</a>
    </li>
</ul>
<input runat="server" id="searchBox" type="text" />

ascx.vb code:

Private Sub Page_Load (...
    `other code

    Dim jobsLi As HtmlGenericControl
    Dim jobsBox As HtmlGenericControl
    jobsLi = CType(Page.FindControl("searchListItem"), HtmlGenericControl)
    jobsBox = CType(Page.FindControl("searchBox"), HtmlGenericControl)

    `other code
End Sub

When I step through the code jobsLi and jobsBox remain nothing.

dmr
  • 21,811
  • 37
  • 100
  • 138
  • I can't remember for sure, but as you added `runat="server"` to both controls, they should be accessible from the CodeBehind automatically, no? – emerson.marini Oct 29 '13 at 17:22
  • 1
    Also, I think `.FindControl()` is not recursive. But then again, I can't remember. – emerson.marini Oct 29 '13 at 17:25
  • @MelanciaUK: They're not. I don't know if it matters, but the code to find the control is inside the Page_Load function – dmr Oct 29 '13 at 17:25
  • 1
    I just confirmed. It's not recursive. http://www.codinghorror.com/blog/2005/06/recursive-pagefindcontrol.html – emerson.marini Oct 29 '13 at 17:27
  • @MelanciaUK: Thank you! I used a recursive function and now it works. If you write your comment as an answer I will accept it. – dmr Oct 29 '13 at 17:37

1 Answers1

1

.FindControl() doesn't perform the search recursively, so one way to solve it is writing a custom method to do it.

Something around these lines:

private Control FindControlRecursive(Control root, string id) 
{ 
    if (root.ID == id)
    { 
        return root; 
    } 

    foreach (Control c in root.Controls) 
    { 
        Control t = FindControlRecursive(c, id); 
        if (t != null) 
        { 
            return t; 
        } 
    } 

    return null; 
}
emerson.marini
  • 9,331
  • 2
  • 29
  • 46