locked
TreeView - Collapse All Nodes Except SelectedNode's Parent Nodes RRS feed

  • Question

  • User322428247 posted

    Control Markup

    <asp:TreeView ID="tv_Menu" 
             DataSourceId="nav1" 
             OnDataBound="tv_Menu_DataBound" 
             runat="server" />


    Code Behind

    Add more cases for a deeper tree.

    protected void tv_Menu_DataBound(object sender, EventArgs e) {
    tv_Menu.CollapseAll();
    if (tv_Menu.SelectedNode != null) {
    	TreeNode tn = tv_Menu.SelectedNode;
    	switch (tn.Depth) {
    		case 5:
    		tn.Parent.Parent.Parent.Parent.Parent.Expand();
    		tn.Parent.Parent.Parent.Parent.Expand();
    		tn.Parent.Parent.Parent.Expand();
    		tn.Parent.Parent.Expand();
    		tn.Parent.Expand();
    		break;
    
    		case 4:
    		tn.Parent.Parent.Parent.Parent.Expand();
    		tn.Parent.Parent.Parent.Expand();
    		tn.Parent.Parent.Expand();
    		tn.Parent.Expand();
    		break;
    
    		case 3:
    		tn.Parent.Parent.Parent.Expand();
    		tn.Parent.Parent.Expand();
    		tn.Parent.Expand();
    		break;
    
    		case 2:
    		tn.Parent.Parent.Expand();
    		tn.Parent.Expand();
    		break;
    
    		case 1:
    		tn.Parent.Expand();
    		break;
    	}
    }
    }




    Tuesday, October 19, 2010 5:32 AM

All replies

  • User1224194097 posted

    You have to use SelectedNodeChanged Event. SelectedNode will be null in databound event.

    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        //Expand Nodes here
    }


    Tuesday, October 19, 2010 8:37 AM
  • User-371711912 posted

    This is an awful way to write it, and will probably end up on thedailywtf.com.


    You should recursively step though the selected node and its parents to expand them.

    Friday, October 22, 2010 3:31 AM
  • User322428247 posted

    Selected node is not null, the code works.

    Have a better solution key? post some code.

    Friday, October 22, 2010 7:55 AM
  • User-205780277 posted

    Try something like this:

     

    // First Collpase All Nodes
    tv_Menu.CollapseAll();
    
    // Then expand the SelectedNode and ALL its parents until no parent found
    TreeNode tn = tv_Menu.SelectedNode;
    tn.Expand();
    while (tn.Parent != null)
    {
         tn = tn.Parent;
         tn.Expand();
    }

    Thursday, March 10, 2011 2:53 PM
  • User-47646173 posted

    hi ,

    in cs file its ok

    but how this code will be use . any link with aspx file

    please answer

    thanks

    Wednesday, April 24, 2013 4:02 AM