When you record the expanded states the sub-nodes are listed as expanded even if the parent node is collapsed so that is forcing them all open. This update will ignore the child items of collapsed nodes
public void GetExpandedStatus(TreeNode node, List<string> ExpandedNodes)
{
if (node.Expanded.GetValueOrDefault(false))
{
ExpandedNodes.Add(node.ValuePath);
node.ChildNodes.Cast<TreeNode>().ToList().ForEach(a => GetExpandedStatus(a, ExpandedNodes));
}
}
Also in the page load you set the state of the previously expanded nodes before they are loaded into the tree, so put
LoadTransactionMenu
first. I also collapsed all nodes before expanding the ones that need to be expanded.
if (!Page.IsPostBack)
{
LoadTransactionMenu();
if (Session["ExpandedNodes"] != null)
{
TreeView1.CollapseAll();
((List<string>)Session["ExpandedNodes"]).ForEach(a => TreeView1.FindNode(a).Expanded = true);
}
}