我是在甜老师的递归函数的基础上做了一些修改,也实现了,是先生成了科目代码规则数组后,再调用的递归函数!
Dim tr As WinForm.TreeView =Forms("账务查询窗体").Controls("TreeView1")
Dim nd As WinForm.TreeNode
Dim dt As DataTable = DataTables("会计科目表")
tr.StopRedraw()
tr.Nodes.Clear
Dim cd As New List(Of Integer) ''科目代码长度
For Each dr As DataRow In dt.DataRows
If cd.Contains(dr("科目代码").Length)=False And dr.IsNull("科目代码")=False Then
cd.Add(dr("科目代码").Length)
End If
Next
Dim gz() As Integer
gz=cd.ToArray ''科目长度转换为数组
Array.Sort(gz) ''科目长度排序
Dim i As Integer
If gz.Length>0 Then
For i=gz.Length-1 To 0 Step -1 ''
If i>0 Then
gz(i)=gz(i)-gz(i-1)
End If
Next
End If
For Each dr As DataRow In dt.Select("","科目代码")
If dr.IsNull("科目代码") = False AndAlso dr("科目代码").Length = gz(0) Then
nd = tr.Nodes.Add(dr("科目代码"),dr("科目代码") & " " & dr("科目名称"))
Functions.Execute("科目树递归函数",nd,dt,gz,1)
End If
Next
tr.ResumeRedraw()
科目树递归函数:
Dim nd As WinForm.TreeNode = args(0)
Dim dt As DataTable = args(1)
Dim gz() As Integer = args(2)
Dim idx As Integer = args(3)
If idx < gz.Length Then
For Each dr As DataRow In dt.Select("","科目代码") '按代码顺序添加
Dim km As String = dr("科目代码")
If km.StartsWith(nd.name) AndAlso km.Length = nd.Name.Length + gz(idx) Then
Dim sum As Integer = 0
For i As Integer = 0 To gz.Length - 1
sum += gz(i)
If km.Length = sum Then
Dim cd As Winform.TreeNode = nd.Nodes.Add(km,km & " " & dr("科目名称"))
Functions.Execute("科目树递归函数",cd,dt,gz,idx+1)
Exit For
End If
Next
End If
Next
End If