基于官方的递归文档案例,适当修改代码,可以判断出递归死循环的路线,及时停止(思路来自最新版Bom目录树玩法)
每条分支,都不应该重复利用主键
不同分支,可以重复利用主键,毕竟bom会重复利用
所以:在每条分支,都用一个空白的字典,记录主键,保持不重复。如果重复,就遍历出来展示告知用户
Dim tr As WinForm.TreeView = e.Form.Controls("TreeView1") Dim nd As WinForm.TreeNode Dim dt As DataTable = DataTables("表A") tr.StopRedraw() tr.Nodes.Clear tr.Nodes.Add("全部") Dim dgDic As New Dictionary(of String,String)'递归记录,防止死循环 For Each dr As DataRow In dt.datarows If dr.IsNull("父键") Then nd = tr.Nodes.Add(dr("键"),dr("标题")) Functions.Execute("AddChildren",nd,dt,dgDic) End If dgDic.Clear '一条递归用一套记录 Next tr.ResumeRedraw()
Dim nd As WinForm.TreeNode = args(0) Dim dt As DataTable = args(1) Dim dgDic As Dictionary(of String,String) = args(2) Dim drs As List(of DataRow) drs = dt.Select("[父键] = '" & nd.name & "'") For Each dr As DataRow In drs Dim cd As Winform.TreeNode = nd.Nodes.Add(dr("键"),dr("标题")) If dgDic.ContainsKey(dr("键")) = False Then dgDic.Add(dr("键"),dr("标题")) Functions.Execute("AddChildren",cd,dt,dgDic) Else Dim s As String ="出现死循环:" For Each key As String In dgDic.Keys If key = dr("键") Then s &= "[" & dgDic(key) & "]→" Else s &=dgDic(key) & "→" End If Next s &=dr("标题") & "→[" & dgDic(dr("键")) & "]" MessageBox.Show(s) End If Next