How to Assign a TreeNodes Numbering Scheme Based on Position

I have a TreeView control in a Windows Forms application that displays my own subclass of TreeNode. I need to display a number along with each node text denoting its position in the tree, for example 1 for the root, 1.1 for its first child, 1.2 for its second child, etc. I am using C # with .NET 2.0

The best I can think of is, after the tree is built, go to each node, recursively find the parent and add the parent sibling number to the beginning of the node text until you reach the root.

+3
source share
3 answers

You can use the extension so that you can reuse the code and get the path at any time.

Poorly implemented, but gives you an idea.

public static class Extensions
    {
        public static string GetPosition(this TreeNode node)
        {
            string Result = "";
            BuildPath(node, ref Result);
            return Result.TrimStart('.');
        }
        private static void BuildPath(TreeNode node,ref string path)
        {
            path = "." + node.Index + path;
            if (node.Parent != null) 
                BuildPath(node.Parent, ref path);
        }
    }
+1
source

You can subclass TreeNode, add properties, and override as needed.

Or you can assign a property to number tags when you build a tree. The algorithm will depend on how you build the tree (top to bottom and bottom to top, etc.).

More explicit information (code) will help formulate a more explicit answer.

update after OP comment:

Sorry, I do not remember; you need to override TreeView instead. Sort of

public class MyTreeView : System.Windows.Forms.TreeView
{
  // ...

    protected override void OnDrawNode(DrawTreeNodeEventArgs e)
    {
        if (e.Node.Tag != null)
        {
            if (e.Node.Tag.GetType() == typeof(MyDataObject))
            {
                MyDataObject data = (MyDataObject)e.Node.Tag;
                e.Node.Name = data.Number + ". " + data.Name;
            }
        }
     }
}
+2
source

, node , .

void Traverse(TreeNode node, string parentNumber)
{
    string nodeNumber = parentNumber + node.Index.ToString();
    node.Text = nodeNumber;
    string prefix = nodeNumber + ".";
    foreach (TreeNode childNode in node.Nodes)
        Traverse(childNode, prefix);
}

TreeNode ​​ parentNumber.

0

Source: https://habr.com/ru/post/1750020/


All Articles