TreeView 大量節點時需採用 PopulateOnDemand 延遲載入,搭配快取 DataTable 避免重複查詢資料庫,實現高效能無限階層樹狀結構。
CREATE TABLE TreeNodes (
ID INT PRIMARY KEY,
ParentID INT NULL,
NodeName NVARCHAR(100)
)
' 快取完整資料表
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 自動處理回傳與節點擴展適用於組織架構、產品分類、網站地圖等大型樹狀資料呈現。