首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 2.0 TreeView 無限階層載入終極解決方案:PopulateOnDemand + 快取

     編輯:關於ASP.NET

TreeView 大量節點時需採用 PopulateOnDemand 延遲載入,搭配快取 DataTable 避免重複查詢資料庫,實現高效能無限階層樹狀結構。

資料表結構

CREATE TABLE TreeNodes (
    ID INT PRIMARY KEY,
    ParentID INT NULL,
    NodeName NVARCHAR(100)
)

核心程式碼 (VB.NET)

' 快取完整資料表
Function GetTreeTable() As DataTable
    Dim dt As DataTable = CType(HttpContext.Current.Cache("Treeview"), DataTable)
    If dt Is Nothing Then
        Using conn As New SqlConnection(connStr)
            Dim da As New SqlDataAdapter("GetTreeview", conn)
            da.SelectCommand.CommandType = CommandType.StoredProcedure
            dt = New DataTable()
            da.Fill(dt)
            HttpContext.Current.Cache.Insert("Treeview", dt)
        End Using
    End If
    Return dt
End Function

' 遞迴填充節點
Sub PopulateNodes(nodes As TreeNodeCollection, Optional parentID As Integer = 0)
    Dim dt As DataTable = GetTreeTable()
    Dim rows() As DataRow = dt.Select($"ParentID = {parentID}")
    For Each row In rows
        Dim tn As New TreeNode(row("NodeName").ToString(), row("ID").ToString())
        ' 檢查是否有子節點
        If dt.Select($"ParentID = {row("ID")}").Length > 0 Then
            tn.PopulateOnDemand = True
        End If
        nodes.Add(tn)
    Next
End Sub

' 頁面載入
Protected Sub Page_Load(...)
    If Not IsPostBack Then PopulateNodes(TreeView1.Nodes, 0)
End Sub

' 展開時動態載入
Protected Sub TreeView1_TreeNodePopulate(sender, e)
    PopulateNodes(e.Node.ChildNodes, Integer.Parse(e.Node.Value))
End Sub

關鍵優勢

  • 首次載入只讀取根節點,極快
  • 全表快取於記憶體,後續展開零資料庫往返
  • PopulateOnDemand 自動處理回傳與節點擴展

適用於組織架構、產品分類、網站地圖等大型樹狀資料呈現。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved