Good Day,
I have two List of objects (say for e.g. MyObjList as new List(of Integer) ) and based on their indices I want to build up a treeview starting from item 0 and end with last item in the list. I want these objects to appear something like below. I can add first node but then after that can't figure how to add next node as child of each previously added node (if that makes sense). Would appreciate your help. I have attached an image to give better understanding of how I want it to look like as against to what I am getting at the moment based on below answers.
0-->
1
-->
2
-->
3-->
4
Dim myObjList As New List(Of integer)
myObjList.Add("0")
myObjList.Add("1")
myObjList.Add("2")
myObjList.Add("3")
myObjList.Add("4")
Can we achieve this?
If I have got this right, you are trying to add
Nodes
so that theTreeView
looks like this:This is what it would look like manually:
This of course is a real pain and isn't scalable. What I would look at instead is recursively adding child
Nodes
to theTreeView
like such:From the code above you will achieve the same result as seen shown in the screenshot.
The beauty of this is that the code will continue to call
AddMoreChildren
until all items in theList
have been added.Edited to incorporate two lists
If you have two lists then what I would look at doing is bringing them together to create a distinct
List
using Concat and Distinct.This will give you the following output:
Edit based on OP's update
This is what the OP is after based on the update:
This requires a little more code and isn't as neat but it does do the job. In this I have to bring in another variable called
index
. This is purely to keep track of the current index inmainList
instead of usingIf parent.Level
.I also have to manipulate
mainList
quite a bit so I'll try to explain in bits.First let's use Intersect. This is used to get a list where values are found in both
firstList
andsecondList
leaving us with S, A3 and U13:Now that we have these let's go ahead and add them to the
TreeView
:I set
index
to 1 here because I already have the root node and want to start at A3 when I go intoAddMoreChildren
. There has also been a slight change to theAddMoreChildren
method:Next, since you want to branch out from U13 we need to get the index of this. This is done quite simply:
Next we set the U13 as the root node:
The code for
GetLastAddedChildNode
is:Then we manipulate the
mainList
so that we get all values fromfirstList
that aren't insecondList
. This leaves us with ABC, PQ and 1234. We do this by using Except. We can then callAddMoreChildren
and add ABC, PQ and 1234 to U13.We then do the same for the
secondList
usingExcept
. Here is the full code in one full swoop. It may make more sense:Here is a screenshot of the output:
Put together this code for you:
Goes through the list in reverse and adds each node as a child of the last.
EDIT: Did this one too, doesn't require reversing your list