TreeView 树形控件 - asp.net
前台:
<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; } } } }