<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="treeMenu" runat="server" ImageSet="Arrows">
<HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />
<NodeStyle Font-Names="Verdana" Font-Size="8pt" ForeColor="Black" HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" />
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD" HorizontalPadding="0px" VerticalPadding="0px" />
</asp:TreeView>
</div>
</form>
</body>
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dt = new DataTable();
//GetMenuToDataTable("select * from sysMenuTree", dt);
GetMenuToDataTable("select * from treeName", dt);
BindTree(dt, null, "0");
}
}
private readonly string ConnString = @"server=.;database=tree;uid=sa;pwd=******";
private DataTable dt = null;
#region tree
private void BindTree(DataTable dtSource, TreeNode parentNode, string parentID)
{
DataRow[] rows = dtSource.Select(string.Format("fid={0}", parentID));
foreach (DataRow row in rows)
{
TreeNode node = new TreeNode();
node.Text = row["cname"].ToString();
node.Value = row["cid"].ToString();
BindTree(dtSource, node, row["cid"].ToString());
if (parentNode == null)
{
treeMenu.Nodes.Add(node);
}
else
{
parentNode.ChildNodes.Add(node);
}
}
}
private DataTable GetMenuToDataTable(string query, DataTable dt)
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
ada.Fill(dt);
}
return dt;
}
#endregion
}