Fortunately, .NET has some great functionality in the DataTable that makes this pretty easy. Here's how I do it.
First, select your category in this fashion:
SELECT CatId, CatName, ParentCatId FROM category ORDER BY CatName
- Get the result into a single DataTable object.
- Use "DataTable.DefaultView.RowFilter" to set the filter that defines the root (or parent-less) nodes of your category tree. Usually this value will be null or some ID that you have defined as meaning "no parent" (perhaps 0 or -1).
"ParentCatId=0"
- Create new TreeNode (to serve as the root node)
- Add new "RootNode" node to the tree control
- Call RecurseTree(DataTable.DefaultView, RootNode.Nodes)
Method RecurseTree(DataView, TreeNodeCollection)
For each row in the dataview
Create new child node
childNode name = row(CatName)
TreeNodeCollection.Add(childNode)
DataView.Table.DefaultView.RowFilter = "ParentCatId=" & row(CatID)
RecurseTree(DataView.Table.DefaultView, childNode.Nodes)
Next row
With some tweaking this should work for you.
|