VS 2010 How to Populate Treeview from XML using VB-VBForums
Results 1 to 31 of 31

Thread: How to Populate Treeview from XML using VB

  1. #1

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Question How to Populate Treeview from XML using VB

    Hello All.

    I'm trying to create a VB Application with a tree view that can be added to and edited as needed on a daily basis..
    So far, I have a form that contains a Tree view control, text boxes and command buttons for Adding, Renaming and Deleting Tree Nodes.

    Currently, I can add a new node without problem BUT but...if I exit or quit the application and then re-launch the application, any changes made are gone.

    The idea of an XML file was suggested to store and save the changes.

    If I do create an XML file, how to I call it, add to it, and edit it, so that changes are stored locally in a folder?

    Regards,

    KellyName:  Treeview Add Edit Delete Nodes.jpg
Views: 1632
Size:  33.2 KB
    Last edited by kellman; Sep 17th, 2012 at 08:30 PM.

  2. #2
    PowerPoster formlesstree4's Avatar
    Join Date
    Jun 2008
    Location
    On the Internet
    Posts
    3,243

    Re: How to save a treeview node list locally?

    You have to create the saving function yourself using whatever method you feel is necessary, whether that be an INI file (I don't recommend), or an XML file.

  3. #3

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to save a treeview node list locally?

    Quote Originally Posted by formlesstree4 View Post
    You have to create the saving function yourself using whatever method you feel is necessary, whether that be an INI file (I don't recommend), or an XML file.
    Can you help me out with how to go about creating a save function for XML file?

  4. #4
    PowerPoster formlesstree4's Avatar
    Join Date
    Jun 2008
    Location
    On the Internet
    Posts
    3,243

    Re: How to Populate Treeview from XML using VB

    Look into the XmlSerializer class. If you want to use an INI file instead, you can look into my ini library which will actually generate XML for you based on sections, keys, and values for you.

  5. #5

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    Quote Originally Posted by formlesstree4 View Post
    Look into the XmlSerializer class. If you want to use an INI file instead, you can look into my ini library which will actually generate XML for you based on sections, keys, and values for you.
    Formlesstree4,

    Would it be possible to have another moderator help me, or answer my question?

    The web links you are giving me contain nothing that is helpful to me as a beginner.

  6. #6
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: How to Populate Treeview from XML using VB

    Try here: Fill treeview control with data from xml file using LINQ. The code is in C# but you should be able to follow it or run it through an online converter if you need the VB equivalent.

    Once you've got loading the file into a TreeView figured out we can work on adding nodes to the XDocument and saving the changes.
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  7. #7

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    Quote Originally Posted by MattP View Post
    Try here: Fill treeview control with data from xml file using LINQ. The code is in C# but you should be able to follow it or run it through an online converter if you need the VB equivalent.

    Once you've got loading the file into a TreeView figured out we can work on adding nodes to the XDocument and saving the changes.
    Okay this is what I have so far. Thought I would start off with a small "test" program first.

    Code:
    Imports System.Xml
    
    Public Class Form1
        Inherits Form
    
        Public Sub New()
            MyBase.New()
            InitializeComponent()
            BuildTree(TreeView1, XDocument.Load("c:\temp\system.xml"))
        End Sub
    
        Private Sub BuildTree(ByVal treeView As TreeView, ByVal doc As XDocument)
            Dim treeNode As TreeNode = New TreeNode(doc.Root.Name.LocalName)
            treeView.Nodes.Add(treeNode)
            BuildNodes(treeNode, doc.Root)
        End Sub
    
        Private Sub BuildNodes(ByVal treeNode As TreeNode, ByVal element As XElement)
            For Each child As XNode In element.Nodes
                Select Case (child.NodeType)
                    Case XmlNodeType.Element
                        Dim childElement As XElement = CType(child, XElement)
                        Dim childTreeNode As TreeNode = New TreeNode(childElement.Name.LocalName)
                        treeNode.Nodes.Add(childTreeNode)
                        BuildNodes(childTreeNode, childElement)
                    Case XmlNodeType.Text
                        Dim childText As XText = CType(child, XText)
                        treeNode.Nodes.Add(New TreeNode(childText.Value))
                End Select
            Next
        End Sub
    
        Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
    
        End Sub
    End Class
    Name:  Treeview XML to VB.JPG
Views: 1636
Size:  18.3 KB

    Next I will add command buttons. One for Adding a new node. One for Editing a node. One for deleting a node.

    Can you help me with the code?

  8. #8

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    Quote Originally Posted by MattP View Post
    Try here: Fill treeview control with data from xml file using LINQ. The code is in C# but you should be able to follow it or run it through an online converter if you need the VB equivalent.

    Once you've got loading the file into a TreeView figured out we can work on adding nodes to the XDocument and saving the changes.
    Do you have any ideas?

  9. #9
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: How to Populate Treeview from XML using VB

    Take a look at this thread:
    http://www.vbforums.com/showthread.php?679292-Storing-Login-Info-In-XML-File.& Code:
    1. Storing Login Info in XML File
    .

    Post #6 has an example of editing a node.

    Post #8 has examples of adding and removing nodes from the XDocument.

    Once you've made the changes to the XDocument save them and repopulate your TreeView.
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  10. #10

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    Quote Originally Posted by MattP View Post
    Take a look at this thread:
    http://www.vbforums.com/showthread.php?679292-Storing-Login-Info-In-XML-File.& Code:
    1. Storing Login Info in XML File
    .

    Post #6 has an example of editing a node.

    Post #8 has examples of adding and removing nodes from the XDocument.

    Once you've made the changes to the XDocument save them and repopulate your TreeView.
    The posts you refer to are regarding adding usernames and passwords, not tree nodes.

  11. #11
    Frenzied Member MattP's Avatar
    Join Date
    Dec 2008
    Location
    WY
    Posts
    1,227

    Re: How to Populate Treeview from XML using VB

    They're examples of adding, editing and deleting nodes in an XML document, which is what you're loading your TreeView from. Just because it's not the exact same situation doesn't mean that there isn't something to learn there and adapt to your needs.
    This pattern in common to all great programmers I know: they're not experts in something as much as experts in becoming experts in something.

    The best programming advice I ever got was to spend my entire career becoming educable. And I suggest you do the same.

  12. #12

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    Could you point me to the line of code you refer in Post #6 that contains any reference to "editing a node" please, I must be blind.
    HTML Code:
    http://www.vbforums.com/showthread.php?679292-Storing-Login-Info-In-XML-File.& Code:
    Code:
        Public Class Form1
         
            Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
         
                Dim filePath = "C:\Temp\Users.xml"
         
                'Load the .xml file into an XDocument object
                Dim xdoc = XDocument.Load(filePath)
         
                Dim searchUserName = "BSmith"
         
                'Get an XElement where the UserName child node's value is "BSmith"
                'FirstOrDefault means that it will return the 1st instance it finds or Nothing if it isn't found.
                Dim elementByUserName = xdoc...<User>.Where(Function(n) n.<UserName>.Value = searchUserName).FirstOrDefault
         
                'Create a new UserClass object and assign values to the properties
                Dim user As New UserClass With
                    {
                        .UserName = elementByUserName.<UserName>.Value,
                        .Password = elementByUserName.<Password>.Value
                    }
         
                'Change the password
                elementByUserName.<Password>.Value = "Password2"
         
                'Save the changes back to the .xml file
                xdoc.Save(filePath)
         
            End Sub
        End Class
         
        Public Class UserClass
            Public Property UserName As String
            Public Property Password As String
        End Class

  13. #13
    Frenzied Member
    Join Date
    Sep 2006
    Location
    Egypt
    Posts
    1,685

    Re: How to Populate Treeview from XML using VB

    To Save/Load treeview to/from xml file, download this class named TreeViewDataAccess.vb and add it to your project, then to save, use
    Code:
    TreeViewDataAccess.SaveTreeViewData(TreeView1, "g:\treeview_test.xml")
    to load, use
    Code:
    TreeViewDataAccess.LoadTreeViewData(TreeView1, "g:\treeview_test.xml")

  14. #14

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    Quote Originally Posted by 4x2y View Post
    To Save/Load treeview to/from xml file, download this class named TreeViewDataAccess.vb and add it to your project, then to save, use
    Code:
    TreeViewDataAccess.SaveTreeViewData(TreeView1, "g:\treeview_test.xml")
    to load, use
    Code:
    TreeViewDataAccess.LoadTreeViewData(TreeView1, "g:\treeview_test.xml")
    Thanks for the great suggestion!

    Problem. After I add the TreeViewDataAccess Class to my Project and point it to my "test_tree.xml" file, I get the following error message:

    Full Exception Details here:
    Code:
    System.InvalidOperationException was unhandled
      Message=There is an error in XML document (2, 2).
      Source=System.Xml
      StackTrace:
           at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
           at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader)
           at WindowsApplication1.TreeViewDataAccess.LoadTreeViewData(TreeView treeView, String path) in C:\Users\Kelly\Documents\Visual Studio 2010\Projects\XML Treeview\XML Treeview\TreeViewDataAccess.vb:line 137
           at WindowsApplication1.Form1.Button2_Click(Object sender, EventArgs e) in C:\Users\Kelly\Documents\Visual Studio 2010\Projects\XML Treeview\XML Treeview\Form1.vb:line 38
           at System.Windows.Forms.Control.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
           at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ButtonBase.WndProc(Message& m)
           at System.Windows.Forms.Button.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
           at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
           at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
           at WindowsApplication1.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
           at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException: System.InvalidOperationException
           Message=<family xmlns=''> was not expected.
           Source=wvrxzxii
           StackTrace:
                at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderTreeViewData.Read4_TreeViewData()
           InnerException:

    Here is the test_tree.xml contents:

    Code:
    <?xml version="1.0" encoding="utf-8" ?>
    <family>
    <parent>id="grandfather"
        <parent>id="father"
             <parent>id="brother"
                <child>id="niece"
                </child>
             </parent>
             <parent>id="me"
                <child>id="son"</child>
                <child>id="daughter"</child>
             </parent>
             <child>id="sister"</child>
         </parent>
         <parent>id="uncle"
             <parent>id="cousin sister"
                <child>id="second cousin"</child>
             </parent>
             <child>id="cousin brother"</child>
         </parent>
    </parent>
    </family>
    VS2010 Project Code:
    Code:
    Public Class Form1
        Inherits Form
    
        Private Sub BuildTree(ByVal treeView As TreeView, ByVal doc As XDocument)
            Dim treeNode As TreeNode = New TreeNode(doc.Root.Name.LocalName)
            treeView.Nodes.Add(treeNode)
            BuildNodes(treeNode, doc.Root)
        End Sub
    
        Private Sub BuildNodes(ByVal treeNode As TreeNode, ByVal element As XElement)
            For Each child As XNode In element.Nodes
                Select Case (child.NodeType)
                    Case Xml.XmlNodeType.Element
                        Dim childElement As XElement = CType(child, XElement)
                        Dim childTreeNode As TreeNode = New TreeNode(childElement.Name.LocalName)
                        treeNode.Nodes.Add(childTreeNode)
                        BuildNodes(childTreeNode, childElement)
                    Case Xml.XmlNodeType.Text
                        Dim childText As XText = CType(child, XText)
                        treeNode.Nodes.Add(New TreeNode(childText.Value))
                End Select
            Next
        End Sub
    
        Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
    
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            TreeViewDataAccess.SaveTreeViewData(TreeView1, "d:\test_tree.xml")
        End Sub
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
        End Sub
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            TreeViewDataAccess.LoadTreeViewData(TreeView1, "d:\test_tree.xml")
        End Sub
    End Class

    Here is the User Interface:
    Name:  Treeview Test Interface.jpg
Views: 1537
Size:  18.6 KB
    Attached Images Attached Images  

  15. #15
    PowerPoster formlesstree4's Avatar
    Join Date
    Jun 2008
    Location
    On the Internet
    Posts
    3,243

    Re: How to Populate Treeview from XML using VB

    That is a very awkward XML file...is that how it saved? It just...sits weirdly with me for some reason.

  16. #16
    Frenzied Member
    Join Date
    Sep 2006
    Location
    Egypt
    Posts
    1,685

    Re: How to Populate Treeview from XML using VB

    As far as you are going to use this class TreeViewDataAccess then you must load xml file that previously saved by it too. so, build your tree as usual, execute TreeViewDataAccess.SaveTreeViewData then on form_load execute TreeViewDataAccess.LoadTreeViewData

    Here is a smple of XML created by that class
    Code:
    <?xml version="1.0"?>
    <TreeViewData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Nodes>
        <TreeNodeData>
          <Text>Node1</Text>
          <ImageIndex>-1</ImageIndex>
          <SelectedImageIndex>-1</SelectedImageIndex>
          <Checked>false</Checked>
          <Expanded>false</Expanded>
          <Nodes>
            <TreeNodeData>
              <Text>Node6</Text>
              <ImageIndex>-1</ImageIndex>
              <SelectedImageIndex>-1</SelectedImageIndex>
              <Checked>false</Checked>
              <Expanded>false</Expanded>
            </TreeNodeData>
            <TreeNodeData>
              <Text>Node7</Text>
              <ImageIndex>-1</ImageIndex>
              <SelectedImageIndex>-1</SelectedImageIndex>
              <Checked>false</Checked>
              <Expanded>false</Expanded>
            </TreeNodeData>
          </Nodes>
        </TreeNodeData>
        <TreeNodeData>
          <Text>Node2</Text>
          <ImageIndex>-1</ImageIndex>
          <SelectedImageIndex>-1</SelectedImageIndex>
          <Checked>false</Checked>
          <Expanded>false</Expanded>
          <Nodes>
            <TreeNodeData>
              <Text>Node9</Text>
              <ImageIndex>-1</ImageIndex>
              <SelectedImageIndex>-1</SelectedImageIndex>
              <Checked>false</Checked>
              <Expanded>false</Expanded>
            </TreeNodeData>
          </Nodes>
        </TreeNodeData>
      </Nodes>
    </TreeViewData>
    BTW: when i test, i found that the method SaveTreeViewData generates the XML as one line of text which make it too difficult to read or edit in text editor like Notepad, so to let it output the XML as the above sample, replace the original method with the following one
    Code:
        Public Shared Sub SaveTreeViewData(ByVal treeView As TreeView, ByVal path As String)
            'Create as serializer and file to save TreeViewData
            Dim ser As New System.Xml.Serialization.XmlSerializer(GetType(TreeViewData))
            Dim file As New System.IO.FileStream(path, IO.FileMode.Create)
            Dim writer As New System.Xml.XmlTextWriter(file, Nothing)
    
            writer.Formatting = Xml.Formatting.Indented ' ---------> Added by 4x2y
    
            'Generate TreeViewData from TreeView and serialize the file.
            ser.Serialize(writer, New TreeViewData(treeView))
    
            'Tidy up
            writer.Close()
            file.Close()
            file = Nothing
        End Sub

  17. #17

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    [QUOTE=4x2y;4242535]As far as you are going to use this class TreeViewDataAccess then you must load xml file that previously saved by it too. so, build your tree as usual, execute TreeViewDataAccess.SaveTreeViewData then on form_load execute TreeViewDataAccess.LoadTreeViewData

    Here is a smple of XML created by that class
    Code:
    <?xml version="1.0"?>
    <TreeViewData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Nodes>
        <TreeNodeData>
          <Text>Node1</Text>
          <ImageIndex>-1</ImageIndex>
          <SelectedImageIndex>-1</SelectedImageIndex>
          <Checked>false</Checked>
          <Expanded>false</Expanded>
          <Nodes>
            <TreeNodeData>
              <Text>Node6</Text>
              <ImageIndex>-1</ImageIndex>
              <SelectedImageIndex>-1</SelectedImageIndex>
              <Checked>false</Checked>
              <Expanded>false</Expanded>
            </TreeNodeData>
            <TreeNodeData>
              <Text>Node7</Text>
              <ImageIndex>-1</ImageIndex>
              <SelectedImageIndex>-1</SelectedImageIndex>
              <Checked>false</Checked>
              <Expanded>false</Expanded>
            </TreeNodeData>
          </Nodes>
        </TreeNodeData>
        <TreeNodeData>
          <Text>Node2</Text>
          <ImageIndex>-1</ImageIndex>
          <SelectedImageIndex>-1</SelectedImageIndex>
          <Checked>false</Checked>
          <Expanded>false</Expanded>
          <Nodes>
            <TreeNodeData>
              <Text>Node9</Text>
              <ImageIndex>-1</ImageIndex>
              <SelectedImageIndex>-1</SelectedImageIndex>
              <Checked>false</Checked>
              <Expanded>false</Expanded>
            </TreeNodeData>
          </Nodes>
        </TreeNodeData>
      </Nodes>
    </TreeViewData>
    That is incredible!

    So the formatting in XML file that I copied from the Microsoft Support KB article #308063 will not work with Serialization. Good to know!

    Taking the XML format you provided in your example works perfectly!!

    Okay, next I want to ADD and EDIT the Nodes.

    Would I use something like TreeViewDataAccess.ADDTreeViewData or TreeViewDataAccess.EditTreeViewData

    Kelly

  18. #18
    Frenzied Member
    Join Date
    Sep 2006
    Location
    Egypt
    Posts
    1,685

    Re: How to Populate Treeview from XML using VB

    Okay, next I want to ADD and EDIT the Nodes.

    Would I use something like TreeViewDataAccess.ADDTreeViewData or TreeViewDataAccess.EditTreeViewData
    No, just concentrate on working with your TreeView control (adding, deleting, modifying etc...) then when you want to save just call TreeViewDataAccess.SaveTreeViewData

  19. #19

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    Quote Originally Posted by 4x2y View Post
    No, just concentrate on working with your TreeView control (adding, deleting, modifying etc...) then when you want to save just call TreeViewDataAccess.SaveTreeViewData
    Fantastic...brilliant!

    I've added a button to remove a selected node. Is it possible to have a "delete confirmation" Yes/No prompt? (that echo's back the name of node).

    Code:
    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
            TreeView1.SelectedNode.Remove() ' Delete the selected node.
        End Sub
    Kelly

  20. #20
    PowerPoster formlesstree4's Avatar
    Join Date
    Jun 2008
    Location
    On the Internet
    Posts
    3,243

    Re: How to Populate Treeview from XML using VB

    Quote Originally Posted by kellman View Post
    Fantastic...brilliant!

    I've added a button to remove a selected node. Is it possible to have a "delete confirmation" Yes/No prompt? (that echo's back the name of node).

    Code:
    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
            TreeView1.SelectedNode.Remove() ' Delete the selected node.
        End Sub
    Kelly
    Look into the MessageBox class.

  21. #21

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    BTW: when i test, i found that the method SaveTreeViewData generates the XML as one line of text which make it too difficult to read or edit in text editor like Notepad, so to let it output the XML as the above sample, replace the original method with the following one
    Code:
        Public Shared Sub SaveTreeViewData(ByVal treeView As TreeView, ByVal path As String)
            'Create as serializer and file to save TreeViewData
            Dim ser As New System.Xml.Serialization.XmlSerializer(GetType(TreeViewData))
            Dim file As New System.IO.FileStream(path, IO.FileMode.Create)
            Dim writer As New System.Xml.XmlTextWriter(file, Nothing)
    
            writer.Formatting = Xml.Formatting.Indented ' ---------> Added by 4x2y
    
            'Generate TreeViewData from TreeView and serialize the file.
            ser.Serialize(writer, New TreeViewData(treeView))
    
            'Tidy up
            writer.Close()
            file.Close()
            file = Nothing
        End Sub
    I tried your suggestion but it contains the following errors:

    Name:  Treeview Save Method.JPG
Views: 1532
Size:  104.9 KB

  22. #22
    PowerPoster formlesstree4's Avatar
    Join Date
    Jun 2008
    Location
    On the Internet
    Posts
    3,243

    Re: How to Populate Treeview from XML using VB

    You don't just copy and paste the whole method inside another method, that was clearly a subroutine that goes in it's own block.

  23. #23
    Frenzied Member
    Join Date
    Sep 2006
    Location
    Egypt
    Posts
    1,685

    Re: How to Populate Treeview from XML using VB

    @kellman

    Open TreeViewDataAccess code window, go to the sub SaveTreeViewData and replace it with mine.

    For deleting confirmation, show a message box with YesNo buttons then if the user press Yes, delete otherwise ignore the action.

  24. #24

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    Quote Originally Posted by 4x2y View Post
    @kellman

    Open TreeViewDataAccess code window, go to the sub SaveTreeViewData and replace it with mine.

    For deleting confirmation, show a message box with YesNo buttons then if the user press Yes, delete otherwise ignore the action.
    4x2y Thank you.

    I would like to be able to move a node up or down on the tree, similar to the vs2010 built-in node editor.

    Do you think this would be possible with XML?

    Kelly

  25. #25
    Frenzied Member
    Join Date
    Sep 2006
    Location
    Egypt
    Posts
    1,685

    Re: How to Populate Treeview from XML using VB

    Do you think this would be possible with XML?
    Yes, just edit your treeview as you like, the method TreeViewDataAccess.SaveTreeViewData will generate the XML file to reflect the current treeview structure.

  26. #26

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    Name:  Treeview Blank.JPG
Views: 1521
Size:  19.9 KBName:  treeview blank and editor.JPG
Views: 1495
Size:  29.8 KBName:  treeview node manually added.JPG
Views: 1500
Size:  19.9 KB
    Quote Originally Posted by 4x2y View Post
    Yes, just edit your treeview as you like, the method TreeViewDataAccess.SaveTreeViewData will generate the XML file to reflect the current treeview structure.
    When I load my project in VS2010 the treeview window does not display the XML tree. I was hoping to use the built-in Node Editor.

    The only time the tree is visible is at run-time.

    I can still use the Node Editor to manually add a new node to the tree, but that is all.

    This is what my tree looks like after pressing F5.
    Name:  treeview at run-time.JPG
Views: 1516
Size:  21.7 KB

    Any ideas.

    Kelly

  27. #27
    Frenzied Member
    Join Date
    Sep 2006
    Location
    Egypt
    Posts
    1,685

    Re: How to Populate Treeview from XML using VB

    Of course you cannot load the saved treeview at design-time.

    Indeed no way, you have to edit the tree at run-time to be able to save and load.

  28. #28

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    Quote Originally Posted by 4x2y View Post
    Of course you cannot load the saved treeview at design time.
    Okay so my only option would be to use an XML editor.

    Thanks for the confirmation.

  29. #29
    Frenzied Member
    Join Date
    Sep 2006
    Location
    Egypt
    Posts
    1,685

    Re: How to Populate Treeview from XML using VB

    Quote Originally Posted by kellman View Post
    Okay so my only option would be to use an XML editor.
    Yes, try XML Notepad, it is free and simple.

    Note: when you edit the xml, don't change the element names, like <Text>, <ImageIndex>,<Nodes> etc...

  30. #30
    Frenzied Member
    Join Date
    Sep 2006
    Location
    Egypt
    Posts
    1,685

    Re: How to Populate Treeview from XML using VB

    I would like to be able to move a node up or down on the tree, similar to the vs2010 built-in node editor.
    Add two buttons and call MoveTreeNodeUp/MoveTreeNodeUp from their click event
    Code:
        Private Sub MoveTreeNodeUp()
            Dim tvnNodeToMove As TreeNode = TreeView1.SelectedNode
            Dim tvnPrevNode As TreeNode = TreeView1.SelectedNode.PrevNode
    
            If tvnPrevNode IsNot Nothing Then
                TreeView1.BeginUpdate()
                TreeView1.SelectedNode.Remove()
                If tvnPrevNode.Parent IsNot Nothing Then
                    tvnPrevNode.Parent.Nodes.Insert(tvnPrevNode.Index, tvnNodeToMove)
                Else
                    TreeView1.Nodes.Insert(tvnPrevNode.Index, tvnNodeToMove)
                End If
                TreeView1.SelectedNode = tvnNodeToMove
                TreeView1.EndUpdate()
            End If
        End Sub
    
        Private Sub MoveTreeNodeDown()
            Dim tvnNodeToMove As TreeNode = TreeView1.SelectedNode
            Dim tvnNextNode As TreeNode = TreeView1.SelectedNode.NextNode
    
            If tvnNextNode IsNot Nothing Then
                TreeView1.BeginUpdate()
                TreeView1.SelectedNode.Remove()
                If tvnNextNode.Parent IsNot Nothing Then
                    tvnNextNode.Parent.Nodes.Insert(tvnNextNode.Index + 1, tvnNodeToMove)
                Else
                    TreeView1.Nodes.Insert(tvnNextNode.Index + 1, tvnNodeToMove)
                End If
                TreeView1.SelectedNode = tvnNodeToMove
                TreeView1.EndUpdate()
            End If
        End Sub

  31. #31

    Thread Starter
    Junior Member kellman's Avatar
    Join Date
    Apr 2012
    Posts
    24

    Re: How to Populate Treeview from XML using VB

    Quote Originally Posted by 4x2y View Post
    Add two buttons and call MoveTreeNodeUp/MoveTreeNodeUp from their click event
    @4x2y

    That is bloody fantastic!

    I don't understand how you do it, but sir, keep on doing it!!

    Five Gold Stars for your above and beyond SUPERIOR support.



    Kelly

Posting Permissions

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



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.