递归生成树Treeview SqlConnection Conn = new SqlConnection("server=.;database=Test;uid=sa;pwd=sa"); DataSet ds; protected void Page_Load(object sender, EventArgs e) { Conn.Open(); this.createDataSet(); Conn.Close(); this.InitTree(tvMenu.Nodes, "0"); } private DataSet createDataSet()//返回数据库表 { ds = new DataSet(); string sqlStr = "select * from Tree "; SqlDataAdapter cmdSelect = new SqlDataAdapter(sqlStr, Conn); cmdSelect.Fill(ds, "Tree"); return ds; } protected void InitTree(TreeNodeCollection Nds, string parentId)//用递归方法动态生成节点 { DataView dv = new DataView(); TreeNode tmpNode; dv.Table = ds.Tables["Tree"]; dv.RowFilter = "ParentId=" + "'" + parentId + "'"; foreach (DataRowView drv in dv) { tmpNode = new TreeNode(); tmpNode.Value = drv["Id"].ToString(); tmpNode.Text = drv["Name"].ToString(); if (drv["ParentId"].ToString() == "0") { tmpNode.SelectAction = TreeNodeSelectAction.None; } else { tmpNode.NavigateUrl = drv["Url"].ToString();//设置超链接 } tmpNode.ExpandAll();//展开所有子节点 Nds.Add(tmpNode); this.InitTree(tmpNode.ChildNodes, tmpNode.Value); } }