典型代碼
動態加載 TreeView 控件的節點,經常使用以構成動態菜單。
//參數1:當前節點的子節點集合,如 TreeView.Nodes 或 某個節點的子節點集合
//參數2:當前節點的ID (用於從數據庫中尋找當前節點的子節點)
private void DrawTree(TreeNodeCollection nds, string parentID)
{
DataTable dt = mgr.GetListByParent(parentID);//獲取當前節點的全部子節點
TreeNode tmpNd;
for (int i = 0; i < dt.Rows.Count; i++)
{
tmpNd = new TreeNode();
tmpNd.Value = dt.Rows[i]["ITEM_ID"].ToString();
tmpNd.Text = dt.Rows[i]["VALUE"].ToString();
if (!(bool)dt.Rows[i]["ISLEAF"]) //若是不是葉子節點
{
tmpNd.NavigateUrl = string.Format("HierarchyEdit.aspx?ID={0}&DID={1}", dt.Rows[i]["ITEM_ID"].ToString(), DEPT_ID);
}
else //若是是葉子
{
tmpNd.NavigateUrl = string.Format("LeafDetail.aspx?ID={0}&DID={1}", dt.Rows[i]["ITEM_ID"].ToString(), DEPT_ID);
tmpNd.Text = string.Format("<span style=\"color:red \">{0}</span>", tmpNd.Text);
}
tmpNd.Target = "content";
nds.Add(tmpNd);
DrawTree(tmpNd.ChildNodes, dt.Rows[i]["ITEM_ID"].ToString());//遞歸建立子節點
}
}
//調用方法
//繪製根節點,
//DrawTree(this.TVLib.Nodes, "0");