none
Extracting the value from a tree node RRS feed

  • Question

  • Hello All:

    I am new to C#. I am working on OPC Client which results a tree as shown below. I want to parse the tree and extract the value from the nodes (say, for example value from holding registers) and assign in to a local variable. Can anyone provide any suggestions on how to parse a tree in C#?

    Thanks,

    Shwetha.


    • Edited by Shwegc Tuesday, March 6, 2018 3:09 PM
    • Moved by CoolDadTx Tuesday, March 6, 2018 6:55 PM Winforms related
    • Moved by Stanly Fan Wednesday, March 21, 2018 2:47 AM
    Tuesday, March 6, 2018 3:09 PM

All replies

  • Ideally you shouldn't have to. The UI should just be a representation of the real data you have stored. Therefore you can simply work with your data as normal and then update the UI accordingly.

    But if you have a treeview and you want to enumerate it then you'll start with the root nodes (TreeView.Nodes) and then enumerate. Depending upon whether you want to process each node as you get to it or do all the nodes at a particular level first determines how you proceed. Ultimately though it involves looking at each node and then, if it has children, enumerating them. Since we don't know how you built the tree we won't know how to extract the data but a common technique is to store the data in the Tag property. So you can enumerate the nodes and retrieve the data from the property.

    void EnumerateTree ( TreeView tree )
    {
       foreach (TreeNode node in tree.Nodes)
          EnumerateTree(node);
    }
    
    void EnumerateTree ( TreeNode node )
    {
       //Process the current node
       ProcessNode(node);
    
       //Enumerate its children
       foreach (TreeNode child in node.Nodes)
          EnumerateTree(child);
    }
    
    void ProcessNode ( TreeNode node )
    {
       //Get the data - from the Tag?
       var data = node.Tag;
    }


    Michael Taylor http://www.michaeltaylorp3.net

    • Proposed as answer by Stanly Fan Wednesday, March 7, 2018 8:38 AM
    • Unproposed as answer by Stanly Fan Monday, March 12, 2018 9:20 AM
    • Proposed as answer by Stanly Fan Monday, March 12, 2018 9:20 AM
    Tuesday, March 6, 2018 6:55 PM