程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> Asp.net treeview實現無限級樹實現代碼

Asp.net treeview實現無限級樹實現代碼

編輯:ASP.NET基礎

先看看效果圖:

先看看數據庫表的設計,數據表主要包括ID,Name,ParentID這三項,其中ID是主鍵,ParentID對應節點的父節點:


方法一:用遞歸遍歷數據,並將節點逐個添加到treeview中去。
1.先進行數據庫連接和數據的讀取,並將根節點先添加進treeview中,並利用遞歸getTreeView()實現數據的遍歷和添加:
復制代碼 代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TreeNode nodeCategory ;
connection conn = new connection();
List<Category> category = conn.getCategory();
Stack<Category> storeCategory = new Stack<Category>();
storeCategory.Push(category[0]);
nodeCategory = new TreeNode(category[0].Name.Trim(), category[0].Id.Trim());
TreeView1.Nodes.Add(nodeCategory);
getTreeView(storeCategory, category, nodeCategory);
}
}

2.數據遍歷的遞歸函數,比較簡單就不多說了。
復制代碼 代碼如下:
public void getTreeView(Stack<Category> categoryStack,List<Category> categoryList,TreeNode e)
{
Category tmp;
if(categoryStack.Count>0)
{
tmp=categoryStack.Pop();
for(int i=0;i<categoryList.Count;i++)
if(categoryList[i].ParentId.Trim()==tmp.Id.Trim())
{
categoryStack.Push(categoryList[i]);
TreeNode childNote = new TreeNode(categoryList[i].Name.Trim(), categoryList[i].Id.Trim());
e.ChildNodes.Add(childNote);
getTreeView(categoryStack, categoryList, childNote);
}
}
}

方法二:用TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)事件響應來逐個讀取子節點。
1.第一步基本和上一方法的第一步一致,只是要將節點的設置為不展開。
復制代碼 代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
TreeNode nodeCategory ;
connection conn = new connection();
List<Category> category = conn.getCategory();
nodeCategory = new TreeNode(category[0].Name.Trim(), category[0].Id.Trim());
nodeCategory.PopulateOnDemand = true;
nodeCategory.Collapse();
nodeCategory.NavigateUrl = "http://blog.csdn.net/longlongago2000";
nodeCategory.Target = "_blank";
TreeView1.Nodes.Add(nodeCategory);
}
}

2.再改寫TreeView1_TreeNodePopulate(),根據鼠標的點擊得到該節點的ID,然後根據該ID進行數據的讀取,將其下的子節點讀出。
復制代碼 代碼如下:
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
int categoryID = Int32.Parse(e.Node.Value);
connection conn = new connection();
List<Category> category = conn.getCategory();
foreach (Category tmp in category)
{
if (categoryID.ToString() == tmp.ParentId.Trim())
{
TreeNode childNote = new TreeNode(tmp.Name.Trim(), tmp.Id.Trim());
foreach (Category cate in category)
{
if (tmp.Id.Trim() == cate.ParentId.Trim())
{
childNote.PopulateOnDemand = true;
childNote.Collapse();
break;
}
else
childNote.Expand();
}
childNote.NavigateUrl ="http://blog.csdn.net/longlongago2000" ;
childNote.Target = "_blank";
e.Node.ChildNodes.Add(childNote);
}
}

以上兩種方法都可以實現無限級分類,不過第一種方法顯然更好一些,第二種方法不可以實現全部展開功能,而第一種可以。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved