ASP.NET站点导航TreeView控件
事例:从数据库调用数据用TreeView控件显示
前台部分:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TreeView ID="TreeView1" runat="server">
</asp:TreeView>
</div>
</form>
</body>
</html>
后台部分
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace ASP数据绑定控件treeview
{
public partial class Demo2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindTree();
}
private void bindTree()
{
DataTable dt = this.GetTreeData();
this.FillNode(dt, null);
}
private void FillNode(DataTable dt, TreeNode node)
{
DataView dv = new DataView(dt);
if (node == null)
{
dv.RowFilter = "parentid='0'";
}
else
{
dv.RowFilter = "parentid='" + node.Value + "'";
}
foreach (DataRowView drv in dv)
{
TreeNode no = new TreeNode(drv["menuname"].ToString(), drv["menuid"].ToString());
FillNode(dt, no);
if (node == null)
{
this.TreeView1.Nodes.Add(no);
}
else
{
node.ChildNodes.Add(no);
}
}
}
private DataTable GetTreeData()
{
string strcnn = ConfigurationManager.ConnectionStrings["treeCon"].ConnectionString;
using (SqlConnection sqlcnn = new SqlConnection(strcnn))
{
SqlCommand sqlcmm = sqlcnn.CreateCommand();
sqlcmm.CommandText = "select * from MenuTree order by parentid,menuorder";
SqlDataAdapter da = new SqlDataAdapter(sqlcmm);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
}
}
}