Results 1 to 28 of 28

Thread: How to Save a TreeView to Text File?

  1. #1

    Thread Starter
    New Member
    Join Date
    Mar 2008
    Posts
    8

    How to Save a TreeView to Text File?

    I am using the following code, but can save roots only (not nodes).

    Code:
            FileOpen(1, "C:\treeTest.txt", OpenMode.Output)
            For Each nodBB As TreeNode In TreeView1.Nodes
                If nodBB.FullPath = nodBB.Text Then
                    PrintLine(1, nodBB.Text)
                Else
                    PrintLine(1, nodBB.Text)
                End If
            Next nodBB
            FileClose(1)

  2. #2
    Code Monkey wild_bill's Avatar
    Join Date
    Mar 2005
    Location
    Montana
    Posts
    2,993

    Re: How to Save a TreeView to Text File?

    Something like this should work
    vb Code:
    1. Private Sub btnCreateTreeData(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreateTreeData.Click
    2.         'create buffer for storing string data
    3.         Dim buffer As New System.Text.StringBuilder
    4.         'loop through each of the treeview's root nodes
    5.         For Each rootNode As TreeNode In yourTreeView.Nodes
    6.             'call recursive function
    7.             BuildTreeString(rootNode, buffer)
    8.         Next
    9.         'write data to file
    10.         IO.File.WriteAllText("C:\treeTest.txt", buffer.ToString)
    11.     End Sub
    12.  
    13.     Private Sub BuildTreeString(ByVal rootNode As TreeNode, ByRef buffer As System.Text.StringBuilder)
    14.         buffer.Append(rootNode.Text)
    15.         buffer.Append(Environment.NewLine)
    16.         For Each childNode As TreeNode In rootNode.Nodes
    17.             BuildTreeString(childNode, buffer)
    18.         Next
    19.     End Sub

    Edited: added buffer.Append(Environment.NewLine)
    Last edited by wild_bill; Mar 12th, 2008 at 03:43 PM.

  3. #3

    Thread Starter
    New Member
    Join Date
    Mar 2008
    Posts
    8

    Re: How to Save a TreeView to Text File?

    if the data in treeview is big will take time to build text file.

  4. #4
    Code Monkey wild_bill's Avatar
    Join Date
    Mar 2005
    Location
    Montana
    Posts
    2,993

    Re: How to Save a TreeView to Text File?

    I'm going to have to answer with a generic response. The bigger it is, the longer it will take.

  5. #5
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,683

    Re: How to Save a TreeView to Text File?

    Save it as a binary file instead then. Binary Serialisation will be a lot faster.
    I don't live here any more.

  6. #6

    Thread Starter
    New Member
    Join Date
    Mar 2008
    Posts
    8

    Re: How to Save a TreeView to Text File?

    is it possible to save it in HTML file? and how ?

  7. #7
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,020

    Re: How to Save a TreeView to Text File?

    HTML files are created just like textfiles, so the code would be practically identical to the one wild bill posted, you just need to change the file's extension from txt to html.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  8. #8
    Lively Member
    Join Date
    Dec 2020
    Posts
    67

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by wild_bill View Post
    Something like this should work
    vb Code:
    1. Private Sub btnCreateTreeData(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreateTreeData.Click
    2.         'create buffer for storing string data
    3.         Dim buffer As New System.Text.StringBuilder
    4.         'loop through each of the treeview's root nodes
    5.         For Each rootNode As TreeNode In yourTreeView.Nodes
    6.             'call recursive function
    7.             BuildTreeString(rootNode, buffer)
    8.         Next
    9.         'write data to file
    10.         IO.File.WriteAllText("C:\treeTest.txt", buffer.ToString)
    11.     End Sub
    12.  
    13.     Private Sub BuildTreeString(ByVal rootNode As TreeNode, ByRef buffer As System.Text.StringBuilder)
    14.         buffer.Append(rootNode.Text)
    15.         buffer.Append(Environment.NewLine)
    16.         For Each childNode As TreeNode In rootNode.Nodes
    17.             BuildTreeString(childNode, buffer)
    18.         Next
    19.     End Sub

    Edited: added buffer.Append(Environment.NewLine)
    That does work. It saves both the root nodes and the child nodes to disk. But they both save exactly the same. How would you make the parent and child look different so that you could reload them into the same structure?

  9. #9
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,282

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by vb6tovbnetguy View Post
    That does work. It saves both the root nodes and the child nodes to disk. But they both save exactly the same. How would you make the parent and child look different so that you could reload them into the same structure?
    If you expect to be able to identify the relationships between nodes when you read the data then you have to save some identifying data when you write the data. The following code will write out the text of a node, along with a sequential ID and the ID of the parent node. Those IDs are used to rebuild the same structure when reading the data in. I tested it with three levels of nodes but it should work for an arbitrary number of levels.
    vb.net Code:
    1. Imports System.IO
    2.  
    3. Public Class MainForm
    4.  
    5.     Private filePath As String = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "TreeViewTest.txt")
    6.  
    7.     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    8.         Using writer As New StreamWriter(filePath)
    9.             'Start the IDs at zero and they will be incremented from there.
    10.             Dim initialNodeId = 0
    11.  
    12.             'A parent ID of zero indicates a top-level node.
    13.             Dim initialParentNodeId = 0
    14.  
    15.             WriteNodes(writer, TreeView1.Nodes, initialNodeId, initialParentNodeId)
    16.         End Using
    17.     End Sub
    18.  
    19.     Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    20.         'Clear the current nodes.
    21.         TreeView1.Nodes.Clear()
    22.  
    23.         'Read in a list of nodes with their ID and parent ID.
    24.         Dim nodeDatas = File.ReadLines(filePath).
    25.                              Select(Function(line)
    26.                                         Dim parts = line.Split(";"c)
    27.  
    28.                                         Return New NodeData With {.NodeId = CInt(parts(0)),
    29.                                                                   .ParentNodeId = CInt(parts(1)),
    30.                                                                   .Node = New TreeNode(parts(2))}
    31.                                     End Function).
    32.                              ToArray()
    33.  
    34.         'Add each node to the child collection of its parent.
    35.         For Each nodeData In nodeDatas.Where(Function(nd) nd.ParentNodeId <> 0)
    36.             Dim parentNode = nodeDatas.First(Function(nd) nd.NodeId = nodeData.ParentNodeId).Node
    37.  
    38.             parentNode.Nodes.Add(nodeData.Node)
    39.         Next
    40.  
    41.         'Add the parent nodes to the TreeView.
    42.         TreeView1.Nodes.AddRange(nodeDatas.Where(Function(nd) nd.ParentNodeId = 0).
    43.                                            Select(Function(nd) nd.Node).
    44.                                            ToArray())
    45.     End Sub
    46.  
    47.     Private Sub WriteNodes(writer As TextWriter, nodes As TreeNodeCollection, ByRef nodeId As Integer, parentNodeId As Integer)
    48.         For Each node As TreeNode In nodes
    49.             'Increment the ID for each new node.
    50.             nodeId += 1
    51.  
    52.             'Write out the current node.
    53.             writer.WriteLine($"{nodeId};{parentNodeId};{node.Text}")
    54.  
    55.             'Write out the child nodes of the current node.
    56.             WriteNodes(writer, node.Nodes, nodeId, nodeId)
    57.         Next
    58.     End Sub
    59.  
    60. End Class
    61.  
    62. Public Structure NodeData
    63.  
    64.     Public Property NodeId As Integer
    65.     Public Property ParentNodeId As Integer
    66.     Public Property Node As TreeNode
    67.  
    68. End Structure
    Just note that that code assumes that the file it's reading is valid. You might want to build in some validation or, at the very least, some exception handling.

    It's worth noting that, as you're guaranteed only two levels, you could make the file a bit simpler and possibly not use IDs. Unless storing these IDs is a problem though, I'd suggest that you stick with this method that will work for any TreeView.

  10. #10
    Lively Member
    Join Date
    Dec 2020
    Posts
    67

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by jmcilhinney View Post
    Code:
    Imports System.IO
     
    Public Class MainForm
     
        Private filePath As String = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "TreeViewTest.txt")
         Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Using writer As New StreamWriter(filePath)
                'Start the IDs at zero and they will be incremented from there.
                Dim initialNodeId = 0
                 'A parent ID of zero indicates a top-level node.
                Dim initialParentNodeId = 0
                 WriteNodes(writer, TreeView1.Nodes, initialNodeId, initialParentNodeId)
            End Using
        End Sub
         Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            'Clear the current nodes.
            TreeView1.Nodes.Clear()
     
            'Read in a list of nodes with their ID and parent ID.
            Dim nodeDatas = File.ReadLines(filePath).
                                 Select(Function(line)
                                            Dim parts = line.Split(";"c)
                                             Return New NodeData With {.NodeId = CInt(parts(0)),
                                                                      .ParentNodeId = CInt(parts(1)),
                                                                      .Node = New TreeNode(parts(2))}
                                        End Function).
                                 ToArray()
     
            'Add each node to the child collection of its parent.
            For Each nodeData In nodeDatas.Where(Function(nd) nd.ParentNodeId <> 0)
                Dim parentNode = nodeDatas.First(Function(nd) nd.NodeId = nodeData.ParentNodeId).Node
     
                parentNode.Nodes.Add(nodeData.Node)
            Next
             'Add the parent nodes to the TreeView.
            TreeView1.Nodes.AddRange(nodeDatas.Where(Function(nd) nd.ParentNodeId = 0).
                                               Select(Function(nd) nd.Node).
                                               ToArray())
        End Sub
     
        Private Sub WriteNodes(writer As TextWriter, nodes As TreeNodeCollection, ByRef nodeId As Integer, parentNodeId As Integer)
            For Each node As TreeNode In nodes
                'Increment the ID for each new node.
                nodeId += 1
                 'Write out the current node.
                writer.WriteLine($"{nodeId};{parentNodeId};{node.Text}")
                 'Write out the child nodes of the current node.
                WriteNodes(writer, node.Nodes, nodeId, nodeId)
            Next
        End Sub
     
    End Class
     
    Public Structure NodeData
         Public Property NodeId As Integer
        Public Property ParentNodeId As Integer
        Public Property Node As TreeNod
    e
    Thank you very much for this code. It works great. I do hate using code that I don't understand as I can't even make small modifications to it myself. But since it will be a while before I understand this enough to be able to do it myself then I guess I will accept what is give to me with appreciation.

    That being said, how would you modify this code to save/load the checked status of the nodes?
    Last edited by vb6tovbnetguy; Jan 11th, 2021 at 01:19 PM.

  11. #11
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,282

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by vb6tovbnetguy View Post
    how would you modify this code to save/load the checked status of the nodes?
    I took the time to comment the code specifically to help you understand it. Have you taken the time to read it AND to debug it to see exactly what it does? If you have read the comments then you would have seen this:
    'Write out the current node.
    I'm going to go out on a limb and suggest that that is where the current node gets written out. Maybe you should examine how that is actually done and then it may become clear how additional data from the node can also be written out. Once you can write the data out, you can think about reading the data in. That will also require further time and effort but if you do that then you should, at the very least, have some sort of idea of what's required and ask specific questions from there. I'm not inclined to just keep providing more code that you don't understand either. I want to see you at least try to understand what you already have first.

  12. #12
    Lively Member
    Join Date
    Dec 2020
    Posts
    67

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by jmcilhinney View Post
    Code:
        Private Sub WriteNodes(writer As TextWriter, nodes As TreeNodeCollection, ByRef nodeId As Integer, parentNodeId As Integer)
            For Each node As TreeNode In nodes
                'Increment the ID for each new node.
                nodeId += 1
    
                'Write out the current node.
                writer.WriteLine($"{nodeId};{parentNodeId};{node.Text}")
    
                'Write out the child nodes of the current node.
                WriteNodes(writer, node.Nodes, nodeId, nodeId)
            Next
        End Sub
    I am wondering about this procedure.

    Code:
    WriteNodes(writer, node.Nodes, nodeId, nodeId)
    How does this line know that there are child nodes? I see that it calls the procedure itself and passes arguments to itself, and if the 2nd argument is null then it can't write it, but what of the 3rd and 4th in that case?

    Quote Originally Posted by jmcilhinney View Post
    Code:
    Public Structure NodeData
        Public Property NodeId As Integer
        Public Property ParentNodeId As Integer
        Public Property Node As TreeNode
    End Structure[/HIGHLIGHT]
    Also this. What is it called? It's outside of the class, but not before it in the declarations area?

  13. #13
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,282

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by vb6tovbnetguy View Post
    I am wondering about this procedure.

    Code:
    WriteNodes(writer, node.Nodes, nodeId, nodeId)
    How does this line know that there are child nodes?
    Every TreeNode has a Nodes property that contains its child nodes. If it has no children, that collection will be empty. Inside the method, there is a For Each loop that enumerates that TreeNodeCollection. If the collection is empty, execution never enters the loop. It's not so much that the method knows that there are no child nodes. It's that the method performs an action once for each node in the collection it receives. If it receives an empty collection then it performs that action zero times.
    Quote Originally Posted by vb6tovbnetguy View Post
    I see that it calls the procedure itself and passes arguments to itself, and if the 2nd argument is null then it can't write it
    The second argument cannot ever be Nothing. It is ALWAYS a TreeNodeCollection. It's just a matter of how many items are in that collection.
    Quote Originally Posted by vb6tovbnetguy View Post
    what of the 3rd and 4th in that case?
    Look at the method declaration and how the parameters are used within the method. The third parameter is the current node ID, which is incremented every time a new node is encountered. That parameter is declared ByRef so that changes made to it within the method are reflected after the method returns. That's how sequentially increasing node IDs can be used as execution goes into and out of calls to that method. If a node has an ID of N and it has M children then, when that method is called, N is passed in via that parameter and (N+M) will come back out, so that (N+M+1) can then be used as the ID for the next sibling. If you debugged the code then you would have seen that.

    The fourth parameter is the parent node ID. When the method is called, the current node ID and the parent node ID are the same, because the parent node is the current node. As children of that parent are enumerated, the current node ID is incremented by 1 for each one but the parent node ID remains the same, because the children all have the same parent.
    Quote Originally Posted by vb6tovbnetguy View Post
    Also this. What is it called? It's outside of the class, but not before it in the declarations area?
    As the code suggests, it is a structure. Structures are types, just like classes. They are very similar to classes in many ways but they are normally used for fairly simple types and, preferably, should be immutable, i.e. cannot be changed once created. I didn't make this structure explicitly immutable for simplicity but it is used that way. If you hear talk about value types and reference types, that basically means structures and classes. Other than String, which is a class, all the basic types that you use (Integer, Double, Date, Boolean, etc) are structures.

  14. #14
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,344

    Re: How to Save a TreeView to Text File?

    FWIW I'd use XML.

    Code:
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim tv As XElement
            tv = TreeToXML(TreeView1.Nodes(0)) 'start with root
    
            'tv.Save("path here") 'save to file
    
            'tv = XElement.Load("path here") 'load from file
    
            ' test by recreating
            TreeView2.Nodes.Clear()
            TreeView2.Nodes.Add(TreeFromXML(tv))
        End Sub
    
        Private Function TreeToXML(aTVnd As TreeNode) As XElement
            Dim rv As XElement
            'create the XML node
            rv = <nd chk="n"><%= aTVnd.Text %></nd>
            If aTVnd.Checked Then
                rv.@chk = "y"
            End If
            For Each nd As TreeNode In aTVnd.Nodes ' add children
                rv.Add(TreeToXML(nd))
            Next
            Return rv
        End Function
    
        Private Function TreeFromXML(XE As XElement) As TreeNode
            Dim rv As TreeNode
            If XE.Nodes(0).NodeType = Xml.XmlNodeType.Text Then
                rv = New TreeNode(XE.Nodes(0).ToString) 'create the TV node
                If XE.@chk = "y" Then rv.Checked = True
                For Each el As XElement In XE.Elements 'add children
                    rv.Nodes.Add(TreeFromXML(el))
                Next
            End If
            Return rv
        End Function
    edit:Add TreeNode checked functionality.
    Last edited by dbasnett; Jan 13th, 2021 at 09:24 AM. Reason: add node checked
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  15. #15
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,282

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by dbasnett View Post
    FWIW I'd use XML.
    Given that XML is inherently hierarchical, just like a TreeView, that is a sound plan.

  16. #16
    Lively Member
    Join Date
    Dec 2020
    Posts
    67

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by jmcilhinney View Post
    I took the time to comment the code specifically to help you understand it. Have you taken the time to read it AND to debug it to see exactly what it does? If you have read the comments then you would have seen this:

    I'm going to go out on a limb and suggest that that is where the current node gets written out. Maybe you should examine how that is actually done and then it may become clear how additional data from the node can also be written out. Once you can write the data out, you can think about reading the data in. That will also require further time and effort but if you do that then you should, at the very least, have some sort of idea of what's required and ask specific questions from there. I'm not inclined to just keep providing more code that you don't understand either. I want to see you at least try to understand what you already have first.
    Thanks for the gentle push. I might not be able to swim across the lake, but I'm unlikely to drown.

    It was easy to add a field in Button1 for "Node.Checked". The saved file now has True/False to the right of each item.

    Button2 is much harder. Here is where I've gotten. Is the change I made correct? Please go into more detail on how this code works?

    Code:
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            'Clear the current nodes.
            TreeView.Nodes.Clear()
    
            'Read in a list of nodes with their ID and parent ID. ***And checked status!!!!
            Dim nodeDatas = File.ReadLines(filePath).
                                 Select(Function(line)
                                            Dim parts = line.Split(";"c)
    
                                            Return New NodeData With {.NodeId = CInt(parts(0)),
                                                                      .ParentNodeId = CInt(parts(1)),
                                                                      .Node = New TreeNode(parts(2)),
                                                                      .NodeChecked = CBool(parts(3))} '<-<-<-<-
                                        End Function).
                                 ToArray()
    
            'Add each node to the child collection of its parent.
            For Each nodeData In nodeDatas.Where(Function(nd) nd.ParentNodeId <> 0)
                Dim parentNode = nodeDatas.First(Function(nd) nd.NodeId = nodeData.ParentNodeId).Node
    
                parentNode.Nodes.Add(nodeData.Node)
            Next
    
            'Add the parent nodes to the TreeView.
            TreeView.Nodes.AddRange(nodeDatas.Where(Function(nd) nd.ParentNodeId = 0).
                                               Select(Function(nd) nd.Node).
                                               ToArray())
        End Sub
    
    Public Structure NodeData
    
        Public Property NodeId As Integer
        Public Property ParentNodeId As Integer
        Public Property Node As TreeNode
        Public Property NodeChecked As Boolean
    Last edited by vb6tovbnetguy; Jan 12th, 2021 at 05:19 PM.

  17. #17
    Lively Member
    Join Date
    Dec 2020
    Posts
    67

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by jmcilhinney View Post
    to debug it to see exactly what it does?
    I haven't gotten to the debug portion of my book. You are obviously suggesting that debug is far more than I thought. Have to got a good link that will tell me about it?

  18. #18
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,601

    Re: How to Save a TreeView to Text File?

    Debugging is examining what happens as the code runs, for example seeing which parts of the code actually run (due to If statements etc), what the values of variables etc are, and so on.

    There is a good tutorial here:
    https://docs.microsoft.com/en-gb/vis...r?view=vs-2019

  19. #19
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,282

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by vb6tovbnetguy View Post
    I haven't gotten to the debug portion of my book. You are obviously suggesting that debug is far more than I thought.
    I think that there is general agreement amongst the people who help often around here that debugging is given criminally little emphasis by just about everyone who claims to be teaching people how to program. I think one problem is that it's not sexy, so they give people some meat to digest before getting onto the brussels sprouts and broccoli. As we've seen here though, if you do it that way then you will often find yourself having problems that debugging could help you solve. I often suggest to people that, if they don't know how to debug, they stop what they're doing and learn, because it will save them much time and heartache in the long run. The problem is that code often doesn't do what we think it's doing - even for experienced developers - but if we just read to find issues then we tend to see what we expect to see and just look right past the issue. If you actually watch the code as it executes and see what path it takes and what values it is using, the actual issue will often be glaringly obvious. Even if you don't know how to fix it, at least you can provide us with specific information about what and where the problem is.

  20. #20
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,282

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by vb6tovbnetguy View Post
    Button2 is much harder. Here is where I've gotten. Is the change I made correct? Please go into more detail on how this code works?
    The code I provided already creates a TreeNode and the point here is to set the Checked property of that, so that's what you should do:
    vb.net Code:
    1. 'Read in a list of nodes with their ID and parent ID.
    2. Dim nodeDatas = File.ReadLines(filePath).
    3.                      Select(Function(line)
    4.                                 Dim parts = line.Split(";"c)
    5.  
    6.                                 Return New NodeData With {.NodeId = CInt(parts(0)),
    7.                                                           .ParentNodeId = CInt(parts(1)),
    8.                                                           .Node = New TreeNode(parts(2)) With {.Checked = CBool(parts(3))}}
    9.                             End Function).
    10.                      ToArray()
    In case you weren't aware, those uses of With in that code are called object initialisers. It's basically a means to set properties on a newly created object in a single line of code. If you were to do this:
    vb.net Code:
    1. Dim obj As New SomeType
    2.  
    3. obj.SomeProperty = someValue
    4. obj.SomeOtherProperty = someOtherValue
    then you could use a conventional With block like this:
    vb.net Code:
    1. Dim obj As New SomeType
    2.  
    3. With obj
    4.     .SomeProperty = someValue
    5.     .SomeOtherProperty = someOtherValue
    6. End With
    and you could condense that further using an object initialiser:
    vb.net Code:
    1. Dim obj As New SomeType With {.SomeProperty = someValue, .SomeOtherProperty = someOtherValue}
    You can also combine an object initialiser with a constructor that has parameters:
    vb.net Code:
    1. Dim obj As New SomeType(someArgument) With {.SomeProperty = someValue, .SomeOtherProperty = someOtherValue}
    You can see that, in my code above, I have created a NodeData object and initialised its NodeId, ParentNodeId and Node properties. With that, I am now creating a TreeNode object and initialising its Checked property. The Text property is already being set via the constructor.

    Moving out a level, that code calls File.ReadLines to get an enumerable list of lines from the specified file. The Select method is then called, which enables you to perform a transformation on each item in an enumerable list to create another enumerable list containing the results of those transformations. For example, lets say that you had a list of numbers from 1 to 10 and you wanted to perform the 7x table on them. You could use Select to multiple by 7 and get the results:
    vb.net Code:
    1. 'Create an enumerable list of Integers that starts at 1 and has 10 items.
    2. Dim input = Enumerable.Range(1, 10)
    3.  
    4. 'Perform the 7x table.
    5. Dim output = input.Select(Function(n) n * 7)
    6.  
    7. For Each number In output
    8.     Console.WriteLine(number)
    9. Next
    The code would display the following:
    7
    14
    21
    28
    35
    42
    49
    56
    63
    70
    In the code I originally provided, a list of lines from the file go in and a list of NodeData objects come out. Those NodeData objects are constructed from the lines of the file, with a TreeNode containing the appropriate Text and now Checked value, along with the ID assigned to the node when it was saved and the ID of its parent. Those IDs are then used to reconstruct the hierarchical structure of the original tree.

  21. #21
    Lively Member
    Join Date
    Dec 2020
    Posts
    67

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by jmcilhinney View Post
    'Perform the 7x table.
    Dim output = input.Select(Function(n) n * 7)

    For Each number In output
    Console.WriteLine(number)
    Next
    [/HIGHLIGHT]
    In this code is Output an array? It doesn't look like an array, but seems to be holding many values at once.


    Quote Originally Posted by jmcilhinney View Post
    In the code I originally provided, a list of lines from the file go in and a list of NodeData objects come out. Those NodeData objects are constructed from the lines of the file, with a TreeNode containing the appropriate Text and now Checked value, along with the ID assigned to the node when it was saved and the ID of its parent. Those IDs are then used to reconstruct the hierarchical structure of the original tree.
    Code:
                                            Return New NodeData With {.NodeId = CInt(parts(0)),
                                                                      .ParentNodeId = CInt(parts(1)),
                                                                      .Node = New TreeNode(parts(2)),
                                                                      .NodeChecked = CBool(parts(3))} '<-<-<-<-
    You mentioned the "Checked" property in this text, but not the changes I made to the code. Did you notice? I added "NodeChecked" in the code above and also in the property structure at the bottom. After that I couldn't figure out what to do next.

  22. #22
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,282

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by vb6tovbnetguy View Post
    In this code is Output an array? It doesn't look like an array, but seems to be holding many values at once.
    You can mouse over any variable to see what type it is. I've addressed this a few times before, I think. It's an enumerable list, i.e. something that implements IEnumerable(Of T) and can this be enumerated using a For Each loop. An array is also an enumerable list, but arrays have additional properties of there own. An enumerable list is something that you can get the items from one by one. Various implementations have additional behaviour, e.g. an array also allows random access by index and elements can be set as well as got.
    Quote Originally Posted by vb6tovbnetguy View Post
    You mentioned the "Checked" property in this text, but not the changes I made to the code. Did you notice? I added "NodeChecked" in the code above and also in the property structure at the bottom. After that I couldn't figure out what to do next.
    I didn't mention your changes specifically because they weren't useful. I specified what you should do instead and provided code that showed how to do it. Think about what you're actually trying to achieve. Those Boolean values came from the Checked properties of the nodes. Obviously, then, the point is to get those values back into those Checked properties. Given that you are creating those nodes here:
    Code:
    Return New NodeData With {.NodeId = CInt(parts(0)),
                              .ParentNodeId = CInt(parts(1)),
                              .Node = New TreeNode(parts(2)),
                              .NodeChecked = CBool(parts(3))}
    what's the point of that NodeChecked property to temporarily store the value that will eventually be assigned to the Checked property of that node when you could just set the Checked property of that node there and then, as I demonstrated? Please tell me that you scrolled the code I provided and saw where I demonstrated that.

  23. #23
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Pointless Forest 38.517,-92.023
    Posts
    9,344

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by vb6tovbnetguy View Post
    I haven't gotten to the debug portion of my book. You are obviously suggesting that debug is far more than I thought. Have to got a good link that will tell me about it?
    si_the_geek provide a debug reference earlier, here is another https://docs.microsoft.com/en-us/vis...r?view=vs-2019
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  24. #24
    Frenzied Member
    Join Date
    Nov 2017
    Posts
    1,385

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by vb6tovbnetguy View Post
    I haven't gotten to the debug portion of my book.
    Probably a good idea to put a bookmark wherever you currently are in your book and skip ahead to debugging. Most programming books shove Debugging as a late chapter or even an Appendix, but the content can (and should, in my opinion) easily be covered much earlier than that, and the ability to debug code is useful at any stage of programming expertise.

  25. #25
    Lively Member
    Join Date
    Dec 2020
    Posts
    67

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by jmcilhinney View Post
    Code:
    Return New NodeData With {.NodeId = CInt(parts(0)),
                              .ParentNodeId = CInt(parts(1)),
                              .Node = New TreeNode(parts(2)),
                              .NodeChecked = CBool(parts(3))}
    what's the point of that NodeChecked property to temporarily store the value that will eventually be assigned to the Checked property of that node when you could just set the Checked property of that node there and then, as I demonstrated? Please tell me that you scrolled the code I provided and saw where I demonstrated that.
    I read everything posted to me, I just don't understand it. You are trying to make me understand calculus when I'm still working on +-*/.

    Your saying I can make the new node that was just create checked. I tried to do that and failed. I don't know how to put it together or where it would go.
    Last edited by vb6tovbnetguy; Jan 13th, 2021 at 08:41 PM.

  26. #26
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    106,282

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by vb6tovbnetguy View Post
    Your saying I can make the new node that was just create checked. I tried to do that and failed. I don't know how to put it together or where it would go.
    Obviously you don't read everything I post because I showed you EXACTLY what to do in post #20. All you have to do is copy and paste the code I provided. I even explained exactly how that code works.
    Code:
    Return New NodeData With {.NodeId = CInt(parts(0)),
                              .ParentNodeId = CInt(parts(1)),
                              .Node = New TreeNode(parts(2)) With {.Checked = CBool(parts(3))}}
    Those NodeData objects are constructed from the lines of the file, with a TreeNode containing the appropriate Text and now Checked value, along with the ID assigned to the node when it was saved and the ID of its parent.

  27. #27
    Lively Member
    Join Date
    Dec 2020
    Posts
    67

    Re: How to Save a TreeView to Text File?

    Quote Originally Posted by jmcilhinney View Post
    Obviously you don't read everything I post because I showed you EXACTLY what to do in post #20. All you have to do is copy and paste the code I provided. I even explained exactly how that code works.
    Code:
    Return New NodeData With {.NodeId = CInt(parts(0)),
                              .ParentNodeId = CInt(parts(1)),
                              .Node = New TreeNode(parts(2)) With {.Checked = CBool(parts(3))}}
    I am really sorry that I couldn't come up with that answer myself. I really tried, but couldn't put together the clues you gave me. I see that the answer is in fact close to my guess.

    The bright point is that even though I couldn't get the answer from your clues, now that you have given me the answer then all the clues do fall together and I understand why the answer is what it is.

    Someday I will understand how all these things work, but that day is not today.
    Last edited by vb6tovbnetguy; Jan 14th, 2021 at 12:13 PM.

  28. #28
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    2,675

    Re: How to Save a TreeView to Text File?

    JMC did give you a nice solution,

    don't know if this sample will help or confuse you, I use this sometimes and save the Treeview to a XML file (well it doesn't really matter if .XML or. txt)
    just a habbit with the extention .xml, you could even save the File as Grocery.grz


    Code:
    Public Class Form1
    
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            'Save Treeview
            Serialize("E:\TestFolder\vb6tovbnetguy.xml", TreeView1)
        End Sub
    
        Private Sub Serialize(ByVal path As String, ByVal t As TreeView)
            Dim f As New IO.FileStream(path, IO.FileMode.Create)
            Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            Dim res(t.Nodes.Count - 1) As TreeNode
            t.Nodes.CopyTo(res, 0)
            bf.Serialize(f, res)
            f.Close()
        End Sub
    
        Private Sub Deserialize(ByVal path As String, ByVal t As TreeView)
            Dim f As New IO.FileStream(path, IO.FileMode.Open)
            Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            t.Nodes.Clear()
            t.Nodes.AddRange(DirectCast(bf.Deserialize(f), TreeNode()))
            f.Close()
            TreeView1.ExpandAll()
        End Sub
    
        Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
            'Load Treeview
            Deserialize("E:\TestFolder\vb6tovbnetguy.xml", TreeView1)
        End Sub
    
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            With TreeView1
                .CheckBoxes = True
                'add some sample Data
                Dim tNode As TreeNode
                tNode = .Nodes.Add("Grocerys")
    
                .Nodes(0).Nodes.Add("Meat")
                .Nodes(0).Nodes(0).Nodes.Add("Pork")
                .Nodes(0).Nodes(0).Nodes.Add("Steak")
                .Nodes(0).Nodes(0).Nodes.Add("Bacon")
    
                .Nodes(0).Nodes.Add("Dairy Products")
                .Nodes(0).Nodes(1).Nodes.Add("Milk")
                .Nodes(0).Nodes(1).Nodes.Add("Yogurt")
    
                .Nodes(0).Nodes.Add("Sweets")
                .Nodes(0).Nodes(2).Nodes.Add("Chocolate")
                .Nodes(0).Nodes(2).Nodes.Add("Winegums")
            End With
            TreeView1.ExpandAll()
        End Sub
    
        Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
            'add to Sweets Node
            Dim SweetsNode As TreeNode
            SweetsNode = TreeView1.Nodes(0).Nodes(2)
    
            SweetsNode.Nodes.Add("Snickers")
            SweetsNode.Nodes.Add("Twix")
        End Sub
    End Class
    Last edited by ChrisE; Jan 14th, 2021 at 12:18 PM.
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width