萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> asp.net編程 >> C#動態綁定treeview控件

C#動態綁定treeview控件

前台只需要放一個 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) //根結點
{
dv.RowFilter = "parentid='0'"; //篩選到根結點的所有子節點
}
else //不是根結點
{
dv.RowFilter = "parentid='" + node.Value + "'"; //篩選對應節點的所有子節點
}
foreach (DataRowView drv in dv) //遍歷填充節點的所有子節點,如果傳入的節點node為葉子節點,遍歷要退出,不再進行遞歸
{
TreeNode no = new TreeNode(drv["menuname"].ToString(), drv["menuid"].ToString());
FillNode(dt, no); //填充no節點的子節點
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];
}
}

copyright © 萬盛學電腦網 all rights reserved