Expand only the selected node in asp.net treeview

well, I created a treeview, but when I try to expand only one node, I faced some problems,
so I try to write this article, to show you how easy you can do this. 

here is the HTML code

<asp:treeview ID="tv" runat="server" ShowLines="True" Width="200px">
            <Nodes>
                <asp:TreeNode Text="Item1" Value="Item1"></asp:TreeNode>
                <asp:TreeNode Text="Item2" Value="Item2">
                    <asp:TreeNode Text="item21" Value="item21"></asp:TreeNode>
                    <asp:TreeNode Text="item22" Value="item22"></asp:TreeNode>
                </asp:TreeNode>
                <asp:TreeNode Text="item3" Value="item3">
                    <asp:TreeNode Text="item31" Value="item31">
                        <asp:TreeNode Text="item311" Value="item311"></asp:TreeNode>
                    </asp:TreeNode>
                </asp:TreeNode>
            </Nodes>
        </asp:treeview>

2e53e447317147b4b99b4e2b1f450f41

first I want to collapse all of the nodes, this by using the ExpandDepth property ExpandDepth="0" 

2e53e447317147b4b99b4e2b1f450f41

now, using the TreeNodeExpanded event I will collapse all the nodes then open the expanded one,
but you must know that when you call the Expand method it will call the TreeNodeExpanded event again, so there will be an infinite loop.

we need to do something before expanding the node.
I will create a bool property to mark that the treeview control has already collapsed once.

the codes looks like

private bool tvCollapsed
    {
        get
        {
            if (ViewState["tvCollapsed"] != null)
                return (bool)ViewState["tvCollapsed"];
            return false;
        }
        set
        {
            ViewState["tvCollapsed"] = value;
        }
    }

and here is the code that will be used to do the required task

protected void tv_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
    {
        if (!tvCollapsed)
        {
            tv.CollapseAll();
            tvCollapsed = true;
        }

      ExpandNode(e.Node);
    }

    private void ExpandNode(TreeNode node)
    {
        node.Expand();
        if (node.Parent != null)
            ExpandNode(node.Parent);

        tvCollapsed = false;
    }

Untitled

filter attribute that checks whether current connection is secured

using APS.net Core to mark all website pages working with https protocol we will do this using IAuthorizationFilter. and here is an exampl...