Fill a TreeView control with random data

Fill a TreeView control with random data

Every now and then you need to fill a TreeView control with some random data, for example when you want to test a routine and you don’t want to write a lot of code just for this secondary task. Here is a recursive routine that does the work for you:

' MaxChildren is the max number of child Nodes at each level' MaxLevel is the deepest nesting level you want to createSub AddRandomNodes(TV As TreeView, Node As Node, MaxChildren As Integer, _    MaxLevel As Integer)    Dim i As Integer    Dim child As Node    ' Add a number of child Nodes less or equal to MaxChildren        For i = 1 To CInt(Rnd * MaxChildren)        Set child = TV.Nodes.Add(Node.index, tvwChild, , _            "Node #" & (TV.Nodes.Count + 1))        ' for each child Node, if MaxLevel is greater than 0        ' randomly add a set of child nodes        If CInt(Rnd * MaxLevel) Then            AddRandomNodes TV, child, MaxChildren, MaxLevel - 1        End If    NextEnd Sub

You can use the above routine as follows:

TreeView1.Nodes.Add , , , "Root"' max 3 levels, max 5 nodes for each levelAddRandomNodes TreeView1, TreeView1.Nodes(1), 5, 3


Share the Post: