ACCESS TreeView控制元件的使用

一曲轻扬發表於2024-04-09

一.在窗體的設計模式下,選擇ActiveX控制元件,然後找到 Microsoft TreeView Control 6.0(SP6) ,確定

二.資料表的設計.重點在處理NodeID與ParentNodeID這兩個欄位的關係上.

三.TreeView資料的載入.下圖是TreeView控制元件的所有事件.可以看到它本身是沒有專用的載入事件的.需要在窗體的Load事件中或者其他事件處理TreeView的資料載入問題.

載入資料:

Tree.Nodes.Clear    '先清空,不然Key 會重複
Dim Rec As DAO.Recordset
Dim Node As Node
Dim isql As String
isql = "SELECT  'S'+MID(CSTR(100000+NodeID),2,5) AS NID ,'S'+MID(CSTR(100000+ParentNodeID),2,5) AS PID,NodeName FROM BomProList where  啟用狀態=-1"
Set Rec = CurrentDb.OpenRecordset(isql)
Rec.MoveLast
n = Rec.RecordCount
Rec.MoveFirst
For i = 0 To n - 1
    If Rec!PID = "S00000" Then
       If n = 1 Then
           Set Node1 = Tree.Nodes.Add(, , "S" & Rec!NID, "無此BOM資料")
       Else
            Set Node1 = Tree.Nodes.Add(, , "S" & Rec!NID, Rec!NodeName)
       End If
    Else
       Set Node1 = Tree.Nodes.Add("S" & Rec!PID, tvwChild, "S" & Rec!NID, Rec!NodeName)
    End If
    Rec.MoveNext
Next
'釋放資源
Rec.Close
Set Rec = Nothing

四.TreeView節點的摺疊與展開

Function TreeExpanded(Tree, Bool)   '設定節點的展開與縮放
    Dim i As Long
    For i = 1 To Tree.Nodes.Count
        Tree.Nodes(i).Expanded = Bool 'True展開所有節點,False 收起所有節點
    Next i
    If Bool Then
        Forms!BOM管理!Command80.Caption = "摺疊"    '設定按鈕的狀態
        Tree.Nodes(1).Selected = True    '展開後tree會被滾動到最底下的節點,需要後動設定,讓捲軸回到tree的第一個節點
    Else
        Forms!BOM管理!Command80.Caption = "展開"
    End If
End Function

相關文章