Fill TreeView with Table data

R

RP

I have an Access Table with following columns:

GID (auto number)
PID number
TreeID Text
ItemName Text

This table consists of records in the following manner:

GID PID TreeID ItemName
----- ------ --------- ------------
1 1 001 RootNode
2 2 001001 Books
3 3 001002 CDs
4 4 001003 Phones
5 2 001001001 Fiction
6 2 001001002 Non-Fiction
7 3 001002001 Pop
8 3 001002002 Classic

Here PID is the ParentID and TreeID is the tag that we want to give to
the node.

Here, the root node TreeID is 001. That is the tag of the root node.
It contains nodes, namely: Books, CDs, Phones with incremental TreeIDs
and prefixed with 001 since they belong to root 001.
Now the Books Node (001001) has child nodes Fiction (001001001) and
Non-Fiction (001001002).
Similarly, CDs Node (001002) has child nodes Pop (001002001) and
Classic (001002002).

I want to fill the TreeView control accordingly at run-time.
I am able to make the root and the main nodes within it. But I am not
able to code how the n number of childs will get accomodated.
 
N

Nicholas Paldino [.NET/C# MVP]

This looks very familiar.

Regardless, it's simple to do.

Cycle through your rows, and for each row, parse out the TreeID. Read
the first three characters, and look for that id in the Nodes collection off
the TreeView instance. If it returns a node, then look for the next three
characters, and so on, and so on. If you don't find the node, then add it.
Then move to the next line.
 
R

RP

Nicholas, it would be good if you can illustrate by code. However,
I'll just try what u suggested.
 
R

RP

Nicholas,

I attempted following code but it gives error in line 15, something
like "NullException" and use the "new" keyword. "Object Reference not
set to an instance of an object"

========================================
1. DataReader dr;
2. string qItems = "Select TreeID, ItemName from Table1 order by
CInt(TreeID)";

3. dr = cmd.ExecuteReader(qItems);

4. while (dr.Read())
5. {
6. string CurrentNodeTagID;

7. CurrentNodeTagID = dr[0].ToString();
8. if (CurrentNodeTagID.Length == 3)
9. TreeView1.Nodes.Add(CurrentNodeTagID, dr[1].ToString());

10. else {
11. string ParentNodeID; // This is CurrentNodeID-3
12. int ParentNodeLength = CurrentNodeID.Length - 3;
13. ParentNodeID = CurrentNodeTagID.SubString(0, ParentNodeLength);

14. //Add this child item to the parent node
15. TreeView1.SelectedNode.Nodes.Add (CurrentNodeTagID,
dr[1].ToString()); }
========================================
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top