前台:
<asp:TreeView ID="TreeView1" runat="server" ImageSet="Msdn" NodeIndent="10" ShowLines="True" ExpandDepth="0"> <ParentNodeStyle Font-Bold="False" /> <NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="5px" NodeSpacing="1px" VerticalPadding="2px" /> <SelectedNodeStyle BackColor="#4a5bb1" ForeColor="white" /> </asp:TreeView>
後台:
//已經定義好的資料protected DataSet ds = new DataSet();CreateTree(this.TreeView1.Nodes,""); //用遞迴的方法顯示樹形目錄 private void CreateTree(TreeNodeCollection TNCs, string strParentId) { TreeNode tmpTNCs = new TreeNode(); DataView dv = new DataView(); dv.Table = ds.Tables[0]; string strID; if (strParentId == "") { dv.RowFilter = "isnull(ParentFunctionID,0)=0"; } else { dv.RowFilter = "ParentFunctionID = " + strParentId; } foreach (DataRowView drv in dv) { tmpTNCs = new TreeNode();//定義結點 strID = drv["subID"].ToString(); tmpTNCs.Value = strID;//定義結點ID tmpTNCs.Text = drv["subName"].ToString();//定義結點文字 //tmpTNCs.ImageUrl = "img/folderclose.gif";//定義圖片 //tmpTNCs.ExpandedImageUrl = "img/folderopen.gif";//定義開啟的圖片 tmpTNCs.NavigateUrl = drv["Url"].ToString();//定義結點聯結 tmpTNCs.Target = "main"; if (tmpTNCs.NavigateUrl == "right.aspx") tmpTNCs.SelectAction = TreeNodeSelectAction.None; //選擇不觸發事件 TNCs.Add(tmpTNCs);//添加結點 CreateTree(TNCs[TNCs.Count - 1].ChildNodes, strID);//遞迴調用 //選定某個結點 if (Request.Params["subID"] != null) { if (strID == Request.Params["subID"].ToString()) { //將選定結點的所有上級結點的Expanded屬性全設為true,即展開結點 string strNodeIndex = TNCs[TNCs.Count - 1].Value; string[] strExpandLevel = strNodeIndex.Split('.'); TreeNode TN = this.TreeView1.Nodes[int.Parse(strExpandLevel[0])]; TN.Expanded = true; for (int i = 1; i < strExpandLevel.Length; i++) { int ii = int.Parse(strExpandLevel[i]); TN = TN.ChildNodes[ii]; TN.Expanded = true; } //選定結點 this.TreeView1.SelectedNode.Value = strNodeIndex; } } } }