Search code examples
asp.netvb.nettreeviewcode-behindexpand

Expanding an ASP.Net TreeView node from code-behind


I'm learning how to access the controls of an ASP.Net master page and trying to expand a particular TreeView node. I'm doing this from another page that is not a master page.

objContentPlaceHolder, objLoginView and objTreeView all have a value as confirmed by using the debugger.

Can you look at this code and let us know why the code in the for loop is not executing? It reaches the for loop but just skips over the for loop at that point.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim objContentPlaceHolder As ContentPlaceHolder
    Dim objLoginView As LoginView
    Dim objTreeView As TreeView

    objContentPlaceHolder = CType(Master.FindControl("ContentPlaceHolderBody"), ContentPlaceHolder)

    If Not objContentPlaceHolder Is Nothing Then

        objLoginView = CType(objContentPlaceHolder.FindControl("loginViewMain"), LoginView)

        If Not objLoginView Is Nothing Then
            objTreeView = CType(objLoginView.FindControl("TreeViewMain"), TreeView)

            ' Make sure all nodes for Maintenance are expanded.
            '--------------------------------------------------
            For Each treenode As TreeNode In objTreeView.Nodes
                If treenode.Text = "Maintenance" Then
                    treenode.Expand()
                End If
            Next treenode
        End If
    End If
End Sub

* Update *

I changed the page load event handler to a PreRenderComplete event handler and would you believe it worked? Not sure why PreRender didn't but that was it. Thanks again everyone for all the help.


Solution

  •    public Sub TreeView_TreeNodeDataBound(ByVal sender As Object, ByVal e As TreeNodeEventArgs  )
           dim mapNode as SiteMapNode =  e.Node.DataItem as SiteMapNode
           If mapNode.Title = "Maintenance" then
               e.Node.Expand()
           End if
       End Sub
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
            Dim objContentPlaceHolder As ContentPlaceHolder
            Dim objLoginView As LoginView
            Dim objTreeView As TreeView
    
            objContentPlaceHolder = CType(Master.FindControl("ContentPlaceHolderBody"), ContentPlaceHolder)
    
            If Not objContentPlaceHolder Is Nothing Then
    
                objLoginView = CType(objContentPlaceHolder.FindControl("loginViewMain"), LoginView)
    
                If Not objLoginView Is Nothing Then
                    objTreeView = CType(objLoginView.FindControl("TreeViewMain"), TreeView)
                    objTreeView.TreeNodeDataBound += TreeView_TreeNodeDataBound 
                End If
            End If
        End Sub
    

    Hope this will help