C# Treeview state expanded

asp.netctreeview

I have a treeview in my masterpage. When a contentpage is loaded i want to save the treeview state (which nodes are collapsed/expanded). I store the nodes in an ArrayList. Code:

private void SaveTreeviewState(TreeNodeCollection nodes)
{
    foreach (TreeNode t in nodes)
    {
        // Store expandable state in ArrayList (true or false)
        //NodePaths.Add(t.Expanded);
        NodePaths.Add(t);

        // Check for childnods
        if (t.ChildNodes.Count > 0)
            // recall this method
            SaveTreeviewState(t.ChildNodes);

    }
}

This method is called by the unload event of the treeview object:

protected void tvManual_Unload(object sender, EventArgs e)
{
    SaveTreeviewState(tvManual.Nodes);

    // Clear session
    Session["Treeview"] = null;

    // Add arraylistm to session
    Session["Treeview"] = NodePaths;

}

In the load event of the masterpage i check whether my Session is set. When the session is set i call the method which read the session.

The arraylist in the session contains all my nodes, so that's correct. However, all nodes have the property expended set to false. This isn't correct because i expanded mupliple nodes.

Hope you guys understand my problem and can help me out.

Thnx in advanced

Best Answer

Because the saved list is actually a list of objects (TreeNode objects), you are actually storing references to the objects. I am guessing that on tvManual_Unload the expanded state is changing or something similar. Probably you are using inprocess session which is similar to having a reference to the objects (there is no serialization) so any change to the object properties are also visible to the objects stored in session.

You could avoid such side effect by storing values into the session. For example store a Dictionary<string, bool> where the key will contain the node path and the value will contain the expanded state.

Related Topic