这次是用递归的方法实现 ,我想大家都知道怎么做吧,就不 多说了,
还是不建议用递归,数据量大了会映响速度,动态生成TreeView方法(一)是我比较喜欢的方法
看一下效果图
前台代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TreeViewPageTwo.aspx.cs" Inherits="WebApplication3.TreeViewPageTwo" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <div> <asp:TreeView id="tv_Method" runat="server"> </asp:TreeView> </div> </form></body></html>
后台代码:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;namespace WebApplication3{public partial class TreeViewPageTwo : System.Web.UI.Page {private DataTable da = new DataTable(); protected void Page_Load(object sender, EventArgs e) {if (!IsPostBack) { da = CreateTable(); CreateNode(); } } //创建父节点 public void CreateNode() { DataRow[] rows = da.Select("parentID=0");//取出树的根节点 if (rows.Length > 0) {foreach (DataRow row in rows) { TreeNode root = new TreeNode();//添加一个节点 root.Value = row["MenuID"].ToString(); root.Text = row["MenuName"].ToString(); root.Expanded = false; root.SelectAction = TreeNodeSelectAction.Expand; tv_Method.Nodes.Add(root); CreateChildNode(root, da);//调用添加子节点 } }else { TreeNode root = new TreeNode();//添加一个节点 root.Value = "为空"; root.Text ="为空"; root.Expanded = false; root.SelectAction = TreeNodeSelectAction.Expand; tv_Method.Nodes.Add(root); } } //创建孩子节点 public void CreateChildNode(TreeNode parentNode, DataTable dt) {//获取父亲节点下面的所有子节点 DataRow[] rows = dt.Select("parentID=" + parentNode.Value);if (rows.Length > 0) {foreach (DataRow row in rows) { TreeNode node = new TreeNode(); node.Value = row["MenuID"].ToString(); node.Text = row["MenuName"].ToString(); node.Expanded = false; node.SelectAction = TreeNodeSelectAction.Expand; parentNode.ChildNodes.Add(node);//递归调用添加子节点 CreateChildNode(node, dt); } } } //创建Table public DataTable CreateTable() { DataTable dt = new DataTable(); dt.Columns.Add("MenuID", Type.GetType("System.Int32")); dt.Columns.Add("parentID", Type.GetType("System.Int32")); dt.Columns.Add("MenuName", Type.GetType("System.String")); DataRow dr = dt.NewRow(); dr["MenuID"] = 1; dr["parentID"] = 0; dr["MenuName"] = "中国"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["MenuID"] = 2; dr["parentID"] = 0; dr["MenuName"] = "日本"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["MenuID"] = 3; dr["parentID"] = 0; dr["MenuName"] = "美国"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["MenuID"] = 4; dr["parentID"] = 1; dr["MenuName"] = "朝阳区"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["MenuID"] = 5; dr["parentID"] = 1; dr["MenuName"] = "海淀区"; dt.Rows.Add(dr); return dt; } }}
时间: 2024-10-25 10:16:46