页面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Tree.aspx.cs" Inherits="MyTeachers.web.Tree" %>
后台
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data;
namespace MyTeachers.web
{
public partial class Tree : System.Web.UI.Page
{
DataView dv;
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
int id =Convert.ToInt32(Session["userID"]);
//数据库执行查询的方法就不写了。
//Operator op = new Operator();
//这里执行的是:select * from tabmenu
dt = BLL.tabMenuBLL.GetAlltabMenut(id);
//第一次加载时调用方法传参
CreateTree(0, null, dt, this.TreeView1);
}
}
///
/// 创建一个树
/// ///
父ID
///
节点
///
DataTable
///
TreeView的名称
public void CreateTree(int parentID, TreeNode node, DataTable dt, TreeView treeView)
{
//实例化一个DataView dt = 传入的DataTable
dv = new DataView(dt);
//筛选(相当于select * from tabMenu where menuParentID = 传入的 parentID)
dv.RowFilter = "[pid]=" + parentID;
//用foreach遍历dv
foreach (DataRowView row in dv)
{
//第一次加载时为空
if (node == null)
{
//创建根节点
TreeNode root = new TreeNode();
//root.Target = "rightFrame";
//必须与数据库的对应
root.Text = row["menuName"].ToString();
root.Value = row["menuID"].ToString();
//添加根节点
this.TreeView1.Nodes.Add(root);
//递归调用方法本身
CreateTree(int.Parse(row["menuID"].ToString()), root, dt, treeView);
}
else
{
//添加子节点
TreeNode childNode = new TreeNode();
childNode.Text = row["menuName"].ToString();
childNode.Value = row["menuID"].ToString();
childNode.NavigateUrl = row["menuUrl"].ToString();
node.ChildNodes.Add(childNode);
CreateTree(int.Parse(row["menuID"].ToString()), childNode, dt, treeView);
}
}
}
}
}