本文展示如何利用递归生成Treeview,满足站点导航的需要。废话不多讲,直接上代码。
一.数据库结构
![](/Images/OutliningIndicators/ContractedBlock.gif)
Code
1 CREATE TABLE [dbo].[MenuTable](
2 [MenuID] [int] IDENTITY(1,1) NOT NULL,
3 [MenuName] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
4 [MenuUrl] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
5 [ParentID] [int] NULL
6 ) ON [PRIMARY]写入几条数据进去 INSERT INTO MenuTable VALUES('网易','http://www.163.com','0')
INSERT INTO MenuTable VALUES('网易邮箱','http://mail.163.com','1')
INSERT INTO MenuTable VALUES('新浪','http://www.sina.com','0')
二.用户控件代码(HTML)
![](/Images/OutliningIndicators/ContractedBlock.gif)
Code
1 <%@ Control Language="C#" AutoEventWireup="true" CodeFile="Navigation.ascx.cs" Inherits="Navigation" %>
2
3 <asp:TreeView ID="tvPet" runat="server"></asp:TreeView>三.后台CS代码
![](/Images/OutliningIndicators/ContractedBlock.gif)
Code
1 using System;
2 using System.Data;
3 using System.Configuration;
4 using System.Collections;
5 using System.Web;
6 using System.Web.Security;
7 using System.Web.UI;
8 using System.Web.UI.WebControls;
9 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;
11
12 using Model;
13 using System.Collections.Generic;
14 using localhost;
15
16 public partial class Navigation : System.Web.UI.UserControl
17 {
18 protected void Page_Load(object sender, EventArgs e)
19 {
20 if (!IsPostBack)
21 {
22 this.ViewState.Add("TreeMenuSource",GetTreeData());
23 InitTreeView(0, null);
24 }
25 }
26
27 /// <summary>
28 /// 递归产生树
29 /// </summary>
30 /// <param name="pid"></param>
31 /// <param name="pNode"></param>
32 protected void InitTreeView(int pid,TreeNode pNode)
33 {
34
35 List<MenuTableInfo> listMT = (List<MenuTableInfo>)this.ViewState["TreeMenuSource"];
36 List<MenuTableInfo> subTreeMenu = listMT.FindAll(delegate(MenuTableInfo mt)
37 {
38 if (mt.ParentID == pid)
39 return true;
40 return false;
41 });
42
43 foreach (MenuTableInfo mInfo in subTreeMenu)
44 {
45 TreeNode node = new TreeNode();
46 node.Text = mInfo.MenuName;
47 node.Expanded = true;
48 node.Value = mInfo.MenuID.ToString();
49 node.NavigateUrl = mInfo.MenuUrl;
50
51 if (pNode == null)
52 {
53 this.tvPet.Nodes.Add(node);
54 }
55 else
56 {
57 pNode.ChildNodes.Add(node);
58 }
59 InitTreeView(mInfo.MenuID, node);
60 }
61 }
62
63 /// <summary>
64 /// 获得TreeView Data
65 /// </summary>
66 /// <returns></returns>
67 protected List<MenuTableInfo> GetTreeData()
68 {
69 GetDateFromServer ws = new GetDateFromServer();
70 List<MenuTableInfo> listMenuTable = new List<MenuTableInfo>();
71 DataTable dt = ws.GetMenuTable().Tables[0];
72
73 foreach (DataRow dr in dt.Rows)
74 {
75 MenuTableInfo mt = new MenuTableInfo();
76 mt.MenuID = Convert.ToInt32(dr["MenuID"]);
77 mt.MenuName = dr["MenuName"].ToString();
78 mt.MenuUrl = dr["MenuUrl"].ToString();
79 mt.ParentID = Convert.ToInt32(dr["ParentID"]);
80 listMenuTable.Add(mt);
81 }
82 return listMenuTable;
83 }
84 }
85 四.效果