1. 程式人生 > >ASP.NET動態建立樹

ASP.NET動態建立樹

樹是一種很好用的導航工具,靜態的樹只要拖控制元件就可以完成,可是有時候需要和資料庫繫結,生成動態的樹,所以我麼就來解決這個問題

第一步:在.aspx前端定義一個樹控制元件:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TreePage.aspx.cs" Inherits="動態樹.TreePage" %>

<!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="dynamicTreeView" runat="server" ShowLines="True">
        </asp:TreeView></span>
    
    </div>
    </form>
</body>
</html>

第二步:在aspx.cs後臺程式去動態的生成樹,新增樹的子節點:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace 動態樹
{
    public partial class TreePage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                LoadTree();
        }
        protected void LoadTree()
        {
            int i=5;
            TreeNode root = new TreeNode();
            root.Text = "Home";
            while(i>0)
            {
                TreeNode child = new TreeNode();
                child.Text = "Child" + i.ToString();
                root.ChildNodes.Add(child);
                i--;

            }
            this.dynamicTreeView.Nodes.Add(root);
        }
    }
}
第三步:在瀏覽器中開啟檢視:

第五步:拓展

         需要根據資料庫或者XML檔案讀取生成樹,只需要在while迴圈的過程中讀取資料庫中的資料即,還可以利用迴圈的巢狀生成結構固定的樹或者是使用資料結構的知識

將資料庫中讀出的亂序的節點建立為一棵導航樹