I have a table with three columns, ID, Name and ParentID. The Identifier column contains the startup number, which also serves as the primary key. The ID will also have the properties node name . The Name column contains a row that will be the treenode Text attribute , and ParentID is the column with the parent identifier node.
This is what my table looks like:
ID Name ParentID
1 A 0
2 A1 1
3 B 0
4 C 0
5 A2 1
6 B1 3
This table shows that node A is the parent node for node A1 and A2. ParentID is "0" means that the parent of the node is the root of the node (hardcoded). For example, node A, B, and C are root node children.
I sort the rows by ParentID until the tree structure is populated. I populate the tree view with these two methods (TreeNode node here is the child node that is populated in the tree):
private void SearchParent(TreeView tree, String parentID, TreeNode node)
{
TreeNodeCollection collection = tree.Nodes;
foreach (TreeNode n in collection)
{
TraverseParent(n, parentID, node);
}
}
private void TraverseParent(TreeNode potentialParent, String parentID, TreeNode node)
{
if (parentID.CompareTo(potentialParent.Name) == 0)
{
potentialParent.Nodes.Add(node);
parentFound = true;
}
else
{
foreach (TreeNode n in potentialParent.Nodes)
{
TraverseParent(n, parentID, node);
}
}
}
Everything is fine as long as I drag the nodes, creating node A a child of node C and committing the changes to the database.
Now my database table is as follows:
ID Name ParentID
1 A 4
2 A1 1
3 B 0
4 C 0
5 A2 1
6 B1 3
The next time I run the application, it will not populate node A1 and A2 in the tree, because it could not find its parents. This is because when I sort the rows based on ParentID before populating the tree structure, the rows are sorted as follows:
ID Name ParentID
3 B 0
4 C 0
2 A1 1
5 A2 1
6 B1 3
1 A 4
Thus, my application will try to populate nodes A1 and A2 in the tree even before creating node A. Therefore, the application could not find a parent for node A1 and A2.
, - ?
.