使用递归法.
函数如下(有些地方使用了自定义函数,自己用的时候可以修改一下):
'/树操作基本参数列表.
Type BaseParameter
Cnn As ADODB.Connection 'ADODB 连接
TrvName As Object '树名称.
TabName As String '树对应的数据表名
ParFld As String '数据表中父节点的字段名.
ChildFld As String '数据表中子节点的字段名.
TextFld As String '数据表中节点文本名称的字段名.
RootIco As String '树中根目录的图标号.
Parico As String '树中父节点的图标号.
ExpParIco As String '树中展表一个节点时的图标号.
ChildIco As String '树中子节点的图标号.
RootText As String '树中根节点的文件.
End Type
Dim TrvBasePar As BaseParameter
'
'单表填充TREEVIEW
'函数:FillTreeView
'参数:SelectSql 一条没有WHERE条件表达式的SELECT语句.
'返回值:
'说明:SELECT语句中必须包括三项:父节点的字段名,子节点的字段名.节点的标签字段名
' 所有节点的KEY值是:G + 节点的ID号.Text值是:节点的标签名.
Public Function FillTreeView(SelectSql As String)
If TrvBasePar.TrvName Is Nothing Then
Exit Function
End If
Call FillTree("", "", SelectSql)
End Function
'/用递归法填充树视图
Private Function FillTree(ParFldValue As String, _
ParKey As String, _
SelectSql As String)
Dim N As Long
Dim NodeX As Node
Dim StrSql As String
Dim Rs As New ADODB.Recordset
Dim RsB As New ADODB.Recordset
Dim ParentArr() As String '记录有子节点的节点
Dim AddId As Long
Dim ChildKey As String, ChileStr As String
Dim Pid As String, PKey As String
Dim TagStr As String
AddId = 0
If Len(ParFldValue) = 0 Then
Set NodeX = TrvBasePar.TrvName.Nodes.Add(, , "G0000", TrvBasePar.RootText, "ROOT")
NodeX.Expanded = True
Call FillTree("0000", "G0000", SelectSql)
Else
StrSql = SelectSql & " Where " & TrvBasePar.ParFld & "='" & ParFldValue & "'"
Set Rs = M_DbCtrl.RsOpen(TrvBasePar.Cnn, StrSql)
If Not (Rs.EOF And Rs.BOF) Then
Rs.MoveFirst
While Not Rs.EOF
ChildKey = "G" & CStr("" & Rs.Fields(TrvBasePar.ChildFld))
Set NodeX = TrvBasePar.TrvName.Nodes.Add(ParKey, tvwChild, ChildKey, _
CStr("" & Rs.Fields(TrvBasePar.TextFld)), TrvBasePar.ChildIco)
StrSql = "Select Top 1 " & TrvBasePar.TabName & "." & TrvBasePar.ChildFld & " From " & TrvBasePar.TabName & _
" Where " & TrvBasePar.ParFld & "='" & CStr("" & Rs.Fields(TrvBasePar.ChildFld)) & "'"
Set RsB = M_DbCtrl.RsOpen(TrvBasePar.Cnn, StrSql)
If Not (RsB.EOF And RsB.BOF) Then
NodeX.Image = TrvBasePar.Parico
AddId = AddId + 1
ReDim Preserve ParentArr(1, AddId)
ParentArr(0, AddId - 1) = CStr("" & Rs.Fields(TrvBasePar.ChildFld))
ParentArr(1, AddId - 1) = CStr("G" & CStr("" & Rs.Fields(TrvBasePar.ChildFld)))
End If
Rs.MoveNext
Wend
Set Rs = Nothing
If AddId > 0 Then
For N = 0 To AddId - 1
Pid = ParentArr(0, N)
PKey = ParentArr(1, N)
Call FillTree(Pid, PKey, SelectSql)
Next
End If
End If
End If
End Function
treeview数据库加载节点
最新推荐文章于 2018-04-11 09:16:04 发布