前臺只需要放一個 treeview控件就行
后臺
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) //根結(jié)點
{
dv.RowFilter = "parentid='0'"; //篩選到根結(jié)點的所有子節(jié)點
}
else //不是根結(jié)點
{
dv.RowFilter = "parentid='" + node.Value + "'"; //篩選對應(yīng)節(jié)點的所有子節(jié)點
}
foreach (DataRowView drv in dv) //遍歷填充節(jié)點的所有子節(jié)點,如果傳入的節(jié)點node為葉子節(jié)點,遍歷要退出,不再進行遞歸
{
TreeNode no = new TreeNode(drv["menuname"].ToString(), drv["menuid"].ToString());
FillNode(dt, no); //填充no節(jié)點的子節(jié)點
if (node == null)
{
this.TreeView1.Nodes.Add(no);
}
else
{
node.ChildNodes.Add(no);
}
}
}
private DataTable GetTreeData()
{
string strcnn = ConfigurationManager.ConnectionStrings["treecnn"].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];
}
}
更多信息請查看IT技術(shù)專欄