TreeView點擊之後保持點擊節點的方法

來源:互聯網
上載者:User

由於微軟的TreeView設計成提交式的,所以有的人寫程式的時候喜歡在把node.NavigateUrl寫成本頁再加上一個參數(我原來也喜歡這麼做),這樣做的後果是一提交之後,treeView又回到原來的樣式,原來點的節點又縮回去,讓使用者不知道點了哪一個節點,網上有很多人給了思路,以下是解決方案。

一:首先在給節點賦值的時候不要給NavigateUrl賦值。把整個TreeView的TreeView1.ExpandDepth設成1級或者二級,看你的情況而定,預設為全部展開。

二:給TreeView添加SelectedNodeChanged事件,如下:

     protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
    {
        string typeId = TreeView1.SelectedNode.Value;
        string typeName = TreeView1.SelectedNode.Text;
        string path = "Default.aspx?typeId=" + typeId + "&typeName=" + Server.UrlEncode(typeName);
        Context.Items["path"] = TreeView1.SelectedNode.ValuePath;
        Server.Transfer(path);
    }

 

三:在Page_load事件加入以下代碼:

     if (!IsPostBack)
     {

               if (Context.Items["path"] != null)
                {
                      TreeNode node = TreeView1.FindNode(Context.Items["path"].ToString()) as TreeNode;
                    if (node != null)
                    {
                        expand(node);
                        node.Selected = true;
                    }
                }
           
        }

 

四:另外寫一個方法 expand(TreeNode node)

   private void expand(TreeNode node)
    {
        if (node.Parent != null)
        {
            node.Parent.Expanded = true;
            expand(node.Parent);
        }
    }

五:設定一下SelectNodeStyle,使選擇的節點滿足您的要求。

 

當然也有牛人手動寫樹,不過要是無限級的話,那可是麻煩事。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.