Monday, November 01, 2010

How to remember the TreeView selection during postbacks

Markup:
<asp:TreeView runat="server" ID="trvItems" EnableClientScript="false" />
<asp:Button runat="server" ID="btnSave" Text="Save" />
 Code:
public partial class Test : Page
{
    protected List<string> SelectedNodes
    {
        get { return (List<string>)(ViewState["TREENODECOLLECTION"] ?? (ViewState["TREENODECOLLECTION"] = new List<string>())); }
        set { ViewState["TREENODECOLLECTION"] = value; }
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        this.trvItems.TreeNodeExpanded += new TreeNodeEventHandler(TreeNodeExpanded);
        this.trvItems.TreeNodeCollapsed += new TreeNodeEventHandler(TreeNodeCollapsed);
        this.trvItems.SelectedNodeChanged += new EventHandler(SelectedNodeChanged);
        if (!this.IsPostBack)
        {
            this.InitalizeTreeView();
            this.trvItems.DataBind();
            this.trvItems.CollapseAll();
            this.SelectedNodes = new List<string>();
        }
        else
            this.SetExapandNodes(this.trvItems.Nodes);
            
    }
    protected void InitalizeTreeView()
    {
 
    }
    protected void SelectedNodeChanged(object sender, EventArgs e)
    {
            
    }
    protected void TreeNodeCollapsed(object sender, TreeNodeEventArgs e)
    {
        this.SelectedNodes.Remove(e.Node.Value);
        this.SetExapandNodes(this.trvItems.Nodes);
    }
    protected void TreeNodeExpanded(object sender, TreeNodeEventArgs e)
    {
        this.SelectedNodes.Add(e.Node.Value);
        this.SetExapandNodes(this.trvItems.Nodes);
    }
    protected void SetExapandNodes(TreeNodeCollection nodes)
    {
        foreach(TreeNode n in nodes)
        {
            if(this.SelectedNodes.Exists(x=>x.Equals(n.Value)))
                n.Expand();
            if(n.ChildNodes.Count>0)
                this.SetExapandNodes(n.ChildNodes);
        }
    }
}

No comments:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...