Can't find Treeview in a RAD AJAX PANEL when used to call user control

3 posts, 0 answers
  1. gonewalkabout
    gonewalkabout avatar
    12 posts
    Member since:
    Oct 2006

    Posted 26 Oct 2011 Link to this post

    I have a dash board style application that uses the Rad Splitter with a Rad Panel. I'm using an Asp.Panel wrapped in a RadAjaxPanel to dynamically call User Controls. (this as a result of a support article dealing with viewstate issues). 

    Two of my user controls use a RadTreeView.
    These controls work great when I use a test.aspx and don't use the RadAjaxPanel.

    But two issues I can't get by and I suspect are related. The Server Side NodeClicked Event is not firing. Other events on the page are so it appears to be specific to RadTreeView.
    I also use the Java code provided in one of the demos to add/delete nodes. I can't seem to find a way to 'find' the treeview control.
    The code  I see recommended ... var treeView;  and  treeView = $find("<%= tvNodes.ClientID %>"); on page load returns a null.

    I did catch one article that suggested that MS Ajax did not support the Treeview? Can you tell me what I'm doing wrong or suggest and alternate way to get this done?

    Code below for the dashboard and the UserControl. 

    USERCONTROL ASPX   -------------------------------------------
    <%@ Control Language="VB" AutoEventWireup="false" CodeFile="InspectionManager.ascx.vb" Inherits="KCCSoft_Web_Controls_InspectionManager" %>

    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
     <script type="text/javascript">
        
         var treeView;
         var textBox;

         function pageLoad() {
             treeView = $find("<%= tvNodes.ClientID %>");
             textBox = $find("<%= tAddNode.ClientID %>");
         }

         function addNode() {
             var nodeText = textBox.get_value();
             var nodelevel = treeView.get_selectedNode();
             if (!nodeText) {
                 alert("Please specify the text for the new node.");
                 return false;
             }

             if (nodelevel.get_level() > 1) {
                 alert("You cannot add a node beyond this level for this tree.");
                 return false;
             }

             treeView.trackChanges();
             //Instantiate a new client node
             var node = new Telerik.Web.UI.RadTreeNode();
             //Set its text
             node.set_text(nodeText);
             //Add the new node as the child of the selected node or the treeview if no node is selected
             var parent = treeView.get_selectedNode() || treeView;
             parent.get_nodes().add(node);
             //Expand the parent if it is not the treeview
             if (parent != treeView && !parent.get_expanded())
                 parent.set_expanded(true);

             treeView.commitChanges();
             return false;
         }

         function deleteNode() {
             var allNodes = treeView.get_allNodes();
             if (allNodes.length < 1) {
                 alert("The treeview is empty.");
                 return false;
             }

             var selectedNode = treeView.get_selectedNode();
             if (!selectedNode) {
                 alert("You need to select a node first.");
                 return false;
             }

             if (allNodes.length == 1) {
                 if (!confirm("This is the last node in the treeview. Are you sure you want to delete it?"))
                     return false;
             }

             treeView.trackChanges();
             var parent = selectedNode.get_parent();
             parent.get_nodes().remove(selectedNode);

             treeView.commitChanges();
             return false;
         }
            </script>
        </telerik:RadCodeBlock>

        <telerik:RadAjaxManagerProxy ID="RadAjaxManagerProxy1" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="ButtonSave">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="CheckList" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
            
        </telerik:RadAjaxManagerProxy>
        <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default">
        </telerik:RadAjaxLoadingPanel>
        
        <telerik:RadSplitter ID="RadSplitter1" runat="server" Width="100%" Height="100%">
            <telerik:RadPane ID="RadPane1" runat="server">
                 <telerik:RadPanelBar ID="rpInspections" runat="server" Width="100%" 
                    ExpandMode="SingleExpandedItem">
                    <Items>
                        <telerik:RadPanelItem runat="server" Text="Inspection and Control Checklist" 
                            Expanded="True">
                            <ContentTemplate>
                                <telerik:RadSplitter ID="RadSplitter2" runat="server">
                                    <telerik:RadPane ID="RadPanelInspectionTree" runat="server" Width="225px">
                                    <div style="padding: 5px">
                                        <label>
                                        Add, Edit or Delete Nodes to Checklist<br />
                                        <telerik:RadTreeView ID="tvNodes" runat="server" DataFieldID="Id" 
                                            DataFieldParentID="ParentId" DataSourceID="sqlNodes" DataTextField="Display" 
                                            DataValueField="Id" >
                                        </telerik:RadTreeView> <br />
                                        Add Node <br />
                                        <telerik:RadTextBox runat="server" ID="tAddNode" > </telerik:RadTextBox>
                                        <asp:ImageButton ID="ButtonSave" runat="server" 
                                            ImageUrl="~/KCCSoft/Images/icon-save.gif" ToolTip="Add Node" 
                                            OnClientClick="return addNode()" /> <br />
                                        Delete Node &nbsp;<asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="~/KCCSoft/Images/icon-delete.gif" ToolTip="Delete Node" OnClientClick="return deleteNode()" /> <br />
                                        <asp:LinkButton ID="SaveInspectionItem" runat="server" onclick="SaveInspectionItem_Click" 
                                           >Save Checklist</asp:LinkButton>
                                        </label>
                                    </div>
                                    </telerik:RadPane>
                                    <telerik:RadPane ID="RadPanelInspectionSitemap" runat="server">
                                       <telerik:RadSiteMap runat="server" ID="SiteMap1" DataSourceID="sqlSiteMap" 
                                        DataFieldID="Id" DataFieldParentID="ParentId" 
                                        DataTextField="Display" DataValueField="Id" Width="100%">
                                            <LevelSettings>
                                                <%-- Settings are initialized from the code-behind --%>
                                                <telerik:SiteMapLevelSetting>
                                                </telerik:SiteMapLevelSetting>
                                                <telerik:SiteMapLevelSetting>
                                                </telerik:SiteMapLevelSetting>
                                                <telerik:SiteMapLevelSetting>
                                                    <NodeTemplate>
                                                        <asp:CheckBox ID="cbNode" runat="server"/>
                                                        <asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Display") %>' Font-Bold="False"></asp:Label>
                                                    </NodeTemplate>
                                                </telerik:SiteMapLevelSetting>
                                            </LevelSettings>
                                        </telerik:RadSiteMap>
                                   </telerik:RadPane>
                                </telerik:RadSplitter>
                                
                            </ContentTemplate>
                        </telerik:RadPanelItem>
                        <telerik:RadPanelItem runat="server" Text="Inspection Workflow Details" Expanded="True" Width="100%">
                            <ContentTemplate>
                               <%-- <uc1:Detail runat="server" ID="InspectionDetail" Width="100%" />--%>
                            </ContentTemplate>
                        </telerik:RadPanelItem>
                        <telerik:RadPanelItem runat="server" Text="Inspection Workflow to Remediate">
                        </telerik:RadPanelItem>
                        <telerik:RadPanelItem runat="server" Text="Supervisor Sign Off and Completion">
                        </telerik:RadPanelItem>
                    </Items>
                </telerik:RadPanelBar>
            </telerik:RadPane>
        </telerik:RadSplitter>
        <asp:HiddenField ID="hNodeId" runat="server" />

        <asp:SqlDataSource ID="sqlSiteMap" runat="server" 
        ConnectionString="<%$ ConnectionStrings:con_commlist %>" 
        SelectCommand="SELECT dbo.uvw_InspectionGetSiteMap.* FROM dbo.uvw_InspectionGetSiteMap WHERE (SiteMap = @sitemap)">
            <SelectParameters>
                <asp:ControlParameter ControlID="hNodeId" DefaultValue="" Name="sitemap" 
                    PropertyName="Value" />
            </SelectParameters>
        </asp:SqlDataSource>
          
        <asp:SqlDataSource ID="sqlNodes" runat="server" 
                ConnectionString="<%$ ConnectionStrings:con_commlist %>" 
                SelectCommand="SELECT Id, ParentId, Display, Description, Expanded FROM dbo.tInspectionAssessment">
        </asp:SqlDataSource>
    END USERCONTROL -------------------------------------------

    USERCONTROL  VB  -------------------------------------------
    Imports System.Data
    Imports System.Data.Sql
    Imports System.Data.SqlClient
    Imports Telerik.Web.UI

    Partial Class KCCSoft_Web_Controls_InspectionManager
        Inherits System.Web.UI.UserControl

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

        Protected Sub ApplyFirstLevelSettings()
            Dim setting As SiteMapLevelSetting = SiteMap1.LevelSettings(0)
            setting.ListLayout.RepeatDirection = SiteMapRepeatDirection.Vertical
            setting.ListLayout.RepeatColumns = 2
            setting.ListLayout.AlignRows = False
        End Sub

        Protected Sub ApplySecondLevelSettings()
            Dim setting As SiteMapLevelSetting = SiteMap1.LevelSettings(1)
            setting.ListLayout.RepeatDirection = SiteMapRepeatDirection.Vertical
            setting.ListLayout.RepeatColumns = 4
            setting.ListLayout.AlignRows = False
        End Sub

        Protected Sub tvNodes_NodeClick(sender As Object, e As Telerik.Web.UI.RadTreeNodeEventArgs) Handles tvNodes.NodeClick
            If tvNodes.SelectedNode.Level = "&H0" Then
                hNodeId.Value = tvNodes.SelectedValue
            End If
        End Sub

        Private Function InspectionChecklist() As UserControl
            Throw New NotImplementedException
        End Function

        Protected Sub SaveInspectionItem_Click(sender As Object, e As System.EventArgs)
            Dim sqlConn As New SqlConnection(ConfigurationManager.ConnectionStrings("con_commlist").ConnectionString)
            Dim insStr As String = "usp_InspectionInsertNewItem"
            Dim delStr As String = "usp_InspectionDeleteItem"
            Dim inscomm As New SqlCommand(insStr, sqlConn)
            inscomm.CommandType = CommandType.StoredProcedure
            inscomm.Parameters.Add("parentid", SqlDbType.Int)
            inscomm.Parameters.Add("display", SqlDbType.VarChar)

            Dim delcomm As New SqlCommand(delStr, sqlConn)
            delcomm.CommandType = CommandType.StoredProcedure
            delcomm.Parameters.Add("nodeid", SqlDbType.Int)

            sqlConn.Open()

            For Each operation As ClientOperation(Of RadTreeNode) In tvNodes.ClientChanges
                Dim node As RadTreeNode = operation.Item
                Select Case operation.Type
                    Case ClientOperationType.Insert
                        Try
                            inscomm.Parameters("parentid").Value = Val(node.ParentNode.Value)
                            inscomm.Parameters("display").Value = node.Text
                            node.Value = inscomm.ExecuteScalar
                        Catch ex As Exception
                        End Try
                        Exit Select
                    Case ClientOperationType.Remove
                        Try
                            delcomm.Parameters("nodeid").Value = Val(node.Value)
                            delcomm.ExecuteNonQuery()
                        Catch ex As Exception
                        End Try
                        Exit Select
                    Case ClientOperationType.Update
                        Dim update As UpdateClientOperation(Of RadTreeNode) = DirectCast(operation, UpdateClientOperation(Of RadTreeNode))
                        'EventLogConsole1.LoggedEvents.Add("The """ + update.PropertyName + """ property of the """ + node.Text + """ node changed.")
                        Exit Select
                End Select
            Next
            sqlConn.Close()
        End Sub
    End Class

    END USERCONTROL -------------------------------------------------

    DASHBOARD.ASPX -----------------------------------------------------------------------
    <%@ Page Title="" Language="VB" MasterPageFile="~/KCCSoft/Web/Master.master" AutoEventWireup="false" CodeFile="Dashboard.aspx.vb" Inherits="Web_Dashboard" %>

    <asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
        <telerik:RadAjaxManagerProxy ID="RadAjaxManagerProxy1" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="NavPanel">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="Panel1" 
                            LoadingPanelID="RadAjaxLoadingPanel1" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManagerProxy>

        <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default">
        </telerik:RadAjaxLoadingPanel>
       
        <div id="container">
        <telerik:RadSplitter id="RadSplitter1" runat="server" height="99%" width="100%">
                    <telerik:RadPane id="LeftPane" runat="server" width="22" Scrolling="None">
                        <telerik:RadSlidingZone id="SlidingZone1" runat="server" width="22"
                        DockedPaneId="Pane1"
                        ExpandedPaneId="Pane1" BorderStyle="None" >
                            <telerik:RadSlidingPane id="Pane1" runat="server" 
                                width="250" minwidth="100" TabView="TextOnly" Title="Expand / Collapse">

            <asp:Login ID="Login1" runat="server" CreateUserText="Register" 
                    PasswordRecoveryText="Recover Password" 
                    VisibleWhenLoggedIn="False">
                </asp:Login>

                <telerik:RadPanelBar ID="NavPanel" runat="server" DataFieldID="Id" 
                    DataFieldParentID="ParentId" 
                    DataSourceID="sqlPanel" DataTextField="Display" DataValueField="Id" 
                    ExpandMode="SingleExpandedItem">
                    
                </telerik:RadPanelBar>
                </telerik:RadSlidingPane>
                </telerik:RadSlidingZone>
                </telerik:RadPane>
                
                <telerik:RadPane id="MainPane" runat="server">
                    <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" 
                        LoadingPanelID="RadAjaxLoadingPanel1" EnableViewState="False">
                        <asp:Panel ID="Panel1" runat="server">
                        </asp:Panel>
                    </telerik:RadAjaxPanel>
                </telerik:RadPane>
        </telerik:RadSplitter>
    </div>

    <asp:SqlDataSource ID="sqlData" runat="server" 
        ConnectionString="<%$ ConnectionStrings:con_commlist %>" 
        SelectCommand="SELECT * FROM [tUserMenus] ORDER BY [Id]">
    </asp:SqlDataSource>

    <asp:SqlDataSource ID="sqlPanel" runat="server" 
        ConnectionString="<%$ ConnectionStrings:con_commlist %>" 
        SelectCommand="usp_GetUserMenus" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:SessionParameter Name="username" SessionField="username" Type="String" />
        </SelectParameters>
    </asp:SqlDataSource>

    </asp:Content>
    END DASHBOARD.ASPX -----------------------------------------------------------------------

    DASHBOARD VB -------------------------------------------------------------
        Protected Sub NavPanel_ItemClick(sender As Object, e As Telerik.Web.UI.RadPanelBarEventArgs) Handles NavPanel.ItemClick
            LoadUserControl(e.Item.Attributes("GoToURL").ToString)
        End Sub

        Public Sub LoadUserControl(controlName As String)
            If Not (LatestLoadedControlName Is Nothing) Then
                Dim previousControl As Control = Panel1.FindControl(LatestLoadedControlName.Split("."c)(0))
                If Not (previousControl Is Nothing) Then
                    Me.Panel1.Controls.Remove(previousControl)
                End If
            End If
            Dim userControlID As String = controlName.Split("."c)(0)
            Dim targetControl As Control = Panel1.FindControl(userControlID)
            If targetControl Is Nothing Then
                Dim userControl As UserControl = CType(Me.LoadControl(controlName), UserControl)
                'slashes and tildes are forbidden
                userControl.ID = userControlID.Replace("/", "").Replace("~", "")
                Me.Panel1.Controls.Add(userControl)
                LatestLoadedControlName = controlName
            End If
        End Sub 'LoadUserControl

        Private Property LatestLoadedControlName() As String
            Get
                Return CStr(ViewState("LatestLoadedControlName"))
            End Get
            Set(value As String)
                ViewState("LatestLoadedControlName") = value
            End Set
        End Property

    END DASHBOARD VB -------------------------------------------------------------

  2. gonewalkabout
    gonewalkabout avatar
    12 posts
    Member since:
    Oct 2006

    Posted 27 Oct 2011 Link to this post

    I went back to the drawing board and started from scratch.
    Working off the assumption that the treeview was getting 'nested' in too many controls I simplified it. I created a user controls with a single radpanelbar. I added a template to the first item and used a simple 1 row, 2 column html table to hold the treeview in one cell and a radsitemap  in the other.
    I then tested the user control by calling it directly from an aspx test page using the RadAjaxPanel method. Note that in the code below I added the bolded line to clear the Panel controls collection but that doesn't seem to effect the issue.

    Everything works great until I call the same method from within the dashboard RadPanel. If I click on any control that has a server side event set the usercontrol simply 'blanks' out ... I can't tell if it destroys itself or is still lurking around somewhere. If I call it from the dashboard panel again it shows up fine. Here's a list of things I've tried / odd behaviours ...
    - if I add a break point to the page load event on the usercontrol it gets hit everytime I call the control load (as I would expect)
    - if I select a node (any node) on the tree the usercontrol blanks out with no warning. If I put a break on the treeview node clicked event it does not get hit HOWEVER if I take the node clicked event out altogether the control does not blank out.
    - I added a button to the user control to see if this was treeview specific ... the same behavior occurs.
    - I noticed that the RadAjaxLoadPanel was getting called BEFORE the usercontrol blanked out, so I removed the RadAjaxPanel and the same behavior occurs.
    So this works ...
    [ASPX] -> RadAjax( [UserControl] ) -> [any server side event
    And this doesn't
    [ASPX] -> [RadSplitter] -> [RadPane] -> [RadPanel] -> [RadPanelItem] -> [Templete] -> [UserControl] -> [any server side event

    I'm left to conclude that something in the nesting of the rad controls (either the splitter or the panel bar / template) is 'loosing' the server side event handler ... but you'd think it would error not just disappear.

    PLEASE HELP ... I'm desperately trying to get a proof of concept working for a corporate client up. He read a white paper that says asp.net development is 10X smart client ... I'm trying to convince him that is only the case if you don't use Telerik controls. I'm not making my point :-(.

        Public Sub LoadUserControl(controlName As String)
            If Not (LatestLoadedControlName Is Nothing) Then
                Dim previousControl As Control = Panel1.FindControl(LatestLoadedControlName.Split("."c)(0))
                If Not (previousControl Is Nothing) Then
                    Me.Panel1.Controls.Remove(previousControl)
                End If
            End If
            Dim userControlID As String = controlName.Split("."c)(0)
            Dim targetControl As Control = Panel1.FindControl(userControlID)
            If targetControl Is Nothing Then
                Dim userControl As UserControl = CType(Me.LoadControl(controlName), UserControl)
                'slashes and tildes are forbidden
                userControl.ID = userControlID.Replace("/", "").Replace("~", "")
                Me.Panel1.Controls.Clear()
                Me.Panel1.Controls.Add(userControl)
                LatestLoadedControlName = controlName
            End If
        End Sub 'LoadUserControl
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Tsvetina
    Admin
    Tsvetina avatar
    1873 posts

    Posted 31 Oct 2011 Link to this post

    Hi,

    When loading user controls dynamically, you should make sure that you recreate them on each Page_Load. Otherwise, the control will not be recreated, as it seems to happen in your scenario. 
    You can read more in our help article on reloading user controls in an AJAX scenario:
    Load User Controls

    Let us know if you notice any other issues afterwards.

    Kind regards,
    Tsvetina
    the Telerik team
    If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
Back to Top