I am trying to construct a TreeView from a Menu. My Code is like this:
public class MenuExtractionUtility
{
public TreeView MenuTraverse(MainMenu mainMenu)
{
TreeView treeView = new TreeView();
TreeNode mainNode = new TreeNode();
foreach (MenuItem mi in mainMenu.MenuItems)
{
System.Diagnostics.Debug.WriteLine(mi.Text);
mainNode.Text = mi.Text;
TreeNode tn = MenuItemTraverse(mi);
mainNode.Nodes.Add(tn);
}
treeView.Nodes.Add(mainNode);
return treeView;
}
private TreeNode MenuItemTraverse(MenuItem menuItem)
{
TreeNode treeNode = new TreeNode();
foreach(MenuItem mi in menuItem.MenuItems)
{
System.Diagnostics.Debug.WriteLine(mi.Text);
treeNode.Text = mi.Text;
TreeNode tr = MenuItemTraverse(mi);
if (tr!=null && tr.Text != "")
{
treeNode.Nodes.Add(tr);
}
}
return treeNode;
}
}
But this is not working.
What can be the problem?
I think there are two problems in the methods. Let’s start with the
MenuItemTraversemethod. You get aMenuItemas input. You declare aTreeNodevariable, and assign a newTreeNodeinstance to it. Then you loop over the menu item’s sub items. For each iteration you assign the text from the sub item to theTreeNode(I would assume that you would want the text of the incoming menu item on thisTreeNode). To get the intended behaviour you should remove this line from the loop:…and add this line before the loop:
It looks like you have the exact same problem in the
MenuTraversemethod, so do the same change there. I think that would solve it for you (didn’t test the code yet; might have missed something).Update
I gave it a bit of though, since I felt that the code could probably be simplified a bit, and this is what I came up with. Instead of having two different methods for
MainMenuandMenuIteminput, this one encapsulates the process into one single method. Also, it takes aTreeNodeCollection, which means that you can have the method inject the menu structure into an already existing (and populated)TreeViewcontrol, at any level in the tree.Usage example:
This code was just quickly put together, so you may want to “stabilize” it a bit by adding null checks and similar.