Search code examples
asp.netvb.netmultidimensional-arrayrunatserver

Accessing server-side control by its ID property in ASP.net


On my default.aspx page I have a bunch of divs with an ID and runat="server":

<div id="serverOne" runat="server"></div>
<div id="serverTwo" runat="server"></div>
<!--etc...-->

In my code behind I've declared a multidimensional array (or grid) with 2 values -- the first being an IP address and the second the server name.

Dim servers = {{"10.0.0.0", "serverOne"}, {"10.0.0.1", "serverTwo"}}

My question is, is there a way where I can target my divs from my code behind using a value from the array?

For i As Integer = 0 To 1

     'This is what I want it to do:
     servers(i, 1).InnerHtml = "<span>Testing " & servers(i, 1) & "</span>"

Next

Solution

  • You can do this using the FindControl method on the page. However, out of the box FindControl looks only at the first level of children, and does not go into the childrens' children. In order to handle this you need to use a helper method that allows FindControl to recursively search through the control hierarchy to find the one you want. Add this method to your code behind, or some shared class that multiple pages can access:

    Protected Function FindControlRecursive(control As Control, id As String)
    
        If (control.ID = id) Then
            Return control
        End If
    
        For Each ctl In control.Controls
    
            Dim foundControl = FindControlRecursive(ctl, id)
    
            If (foundControl IsNot Nothing) Then
                Return foundControl
            End If
    
        Next
    
        Return Nothing
    
    End Function
    

    Once you have that, it's pretty easy to find your <div> just by using the string ID property.

    For i As Integer = 0 To 1
    
        Dim div = CType(FindControlRecursive(Me, servers(i, 1)), HtmlGenericControl)
        div.InnerHtml = "<span>Testing " & servers(i, 1) & "</span>"
    
    Next
    

    Reference: http://forums.asp.net/t/1107107.aspx/1