TreeView 資料庫子母節點

October 12, 2011 0 Comments

In this case , I use MSSQL to save my TreeView node, and recursive loop nodes.
在新的專案中,我將TreeView獨立出成usercontrol並用viewstate去記錄節點的開合狀態,然後放在masterpager中。而TreeView的節點是從資料庫撈取,資料庫的表格大致如下:


撈節點的方式是先建立根節點(判斷Level0是否為true) 然後再用遞迴的方式去新增....
中間再加入一個條件去判斷該使用者是否有該節點的ID值,有就新增。

'主架構
Public Sub BuildTree()

Dim dst As DataSet = GetTreeViewData() '從資料庫把Table撈出來丟到dst
Session("Dt") = dst.Tables("eip_power_tree")

For Each masterRow As DataRow In dst.Tables("eip_power_tree").Rows

If masterRow("Level0") = True Then 'build Root Node
Dim masterNode As New TreeNode(masterRow("ID"), masterRow("ID"))
TreeView1.Nodes.Add(masterNode)
'呼叫建立子節點的函數
AddNodes(masterNode, masterRow("ID"))
End If

Next

End Sub

Function AddNodes(ByRef tNode As TreeNode, ByVal PId As Integer) As String
'******** 遞迴增加樹結構節點 ********
Try

'定義DataTable
Dim Dt As DataTable
'從Session中取得DataTable
Dt = Session("Dt")

'定義DataRow承接DataTable篩選的結果
Dim rows() As DataRow
'定義篩選的條件
Dim filterExpr As String
filterExpr = "UpLevel_id = '" & PId & "'"
'資料篩選並把結果傳入Rows
rows = Dt.Select(filterExpr)

'如果篩選結果有資料
If rows.GetUpperBound(0) >= 0 Then
Dim row As DataRow
Dim tmpNodeId As Long
Dim NewNode As TreeNode


'逐筆取出篩選後資料
For Each row In rows
'和權限table比對
If powerDt.Select("power_tree_ID='" & row(0) & "'").Length > 0 Then
'放入相關變數中
tmpNodeId = row(0)

'實體化新節點
NewNode = New TreeNode
'設定節點各屬性
NewNode.Text = IIf(IsDBNull(row(1)), "", row(1))
NewNode.Value = IIf(IsDBNull(row(6)), "", row(6))
'NewNode.NavigateUrl = tmpsUrl
'NewNode.Target = tmpsTarget
'將節點加入Tree中
tNode.ChildNodes.Add(NewNode)

'呼叫遞回取得子節點
AddNodes(NewNode, tmpNodeId)
End If
Next
End If
Catch ex As Exception
Throw ex
End Try
Return True
End Function


0 comments: