It would depend on what kind of data you want to represent, but at home
I have a program I wrote in C# that stores all my novels in a database,
and represents them in a treeview. Each node is added individually to
the tree. This is a simplistic view of the data schema:
Book : This is the actual novel
Series : All books belong to a series
Group : All Series belong to a group (such as "Science Fiction")
Groups can belong to other groups. For example, the "TSR Novels" group
belongs to the "Science Fiction" group which belongs to the "Fiction"
group.
At run time, the tree displays a root node and under that is all groups
that don't have a parent group id. Then each of those groups adds any
child groups. This is done through "recursion". In all cases, the
program is just iterating through the datatable of groups looking for
any group that has the parent ID of the group it is filling nodes for.
Its slow but, I don't have that many books!
Sorry I don't have code here for you. But its not uncommon to create
MENUs with this kind of concept. Try making a Menu table like this in
your DB:
MenuID int
MenuName nvarchar 50
ParentMenuID int
Usually I would store -1 in ParentMenuID for menu's that are the top
level. Other's might prefer to store NULL instead, or 0, or some other
predetermined negative number.
Add in some fake values manually. Then in your code, return ALL the
rows from your menu table into a datatable. Create your first "ROOT"
node for your treeview. Then put it as a parameter to your recursive
function that may look something like this:
private DataTable AllMenus;
private void LoadNodes(TreeNode ParentNode, int ParentMenuID) {
foreach (DataRow dr in AllMenus.Rows) {
if (dr["ParentMenuID"] == ParentMenuID) {
TreeNode newNode = new TreeNode(dr["MenuName"]);
TreeNode.Tag = dr;
ParentNode.Nodes.Add(newNode);
LoadNodes(newNode, dr["MenuID"]);
}
}
}
When you call "LoadNodes" the first time with your root node, just pass
-1 as the ParentMenuID.
(DISCLAIMER: Code not tested, and note that my type conversions are not
completed.
Hope this helps you out!
Steve
Henry wrote:
Does anybody have a real-world sample of buiding a treeview control using
data from database tables? All the sample code I have found either builds
the treeview manually or uses a file directory as the sample.
I have trouble translating those samples to working with data coming from my
database, so I am hoping that someone could show me a sample of code that
builds a tree from say a dataset.
Many controls you can bind to a datasource, but treeviews, I think, would be
more difficult because of the node structure. How would the application
tell what piece of data belonged at what node level? That is why I would
imagine that you would have to add siginificant code to build the control
up. Am I correct in that assumption?
Here is looking forward to some samples from the gurus out there. Thanks.