Saving TreeView to Database in recursively

Posted on 2006-06-02
Last Modified: 2009-11-18

I am struggling with saving a TreeView structure to a SQL database.

Essentially I am adding Nodes to a tree at runtime.  When I Click a button
I want to save the TreeView in a database.  (Below is an example of
showing treeView create in code)

I have converted some C -code to Vb I found in Experts Exchange but am still
having problems.   Maybe I have been staring at this too long!!!!  
I urgently need to get this resolved....

I will greatly appreciate help!!!

TreeView created at runtime in code using Context Menu
with Add/Delete options
  Add Node code:
    Private Sub AddNode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim xChild As New TreeNode
        Dim xParent As String
        xChild.Text = Me.txtNodeName.Text
        LastNode += 1
        xChild.Tag = LastNode
     End Sub

    Private Sub SaveTree(ByVal TreeView1 As TreeView)
        Dim xNode As TreeNode
        Dim NumNodes = 0
        Dim xNodeName As String
        Call Delete_AllRecord_tblTreeView1()
        For Each xNode In TreeView1.Nodes
            xNodeName = xNode.Text
            NumNodes += 1
            Call SaveRecursive(xNode)
        MsgBox("Number of Nodes =" & Str(NumNodes), MsgBoxStyle.Information, "Total Number of Nodes Saved")
    End Sub      
  Private Sub SaveRecursive(ByVal Node As TreeNode)
        Dim MyId As Integer = Node.Tag
        Dim ParentId As New Integer
        Dim MyName As String = Node.Text
        Dim strSQL As String
        Dim ix As Integer
        Console.WriteLine("MyId = " & MyId)
   '   I this is where I am getting an error....
   '   I am hopeful that if I can get this working the structure will be saved in my database.

        If Not Node.Parent Is Nothing Then
           ParentId = Int(Node.Parent.Tag)     '===> Error saying New Instance of Object required
        End If

        strSQL = " INSERT INTO tblTreeView1 "
        strSQL += "(TvNodeId, TvParentId, TvNodeName, TvPermission) "
        strSQL += " VALUES ( "
        strSQL += Str(MyId) & ", "
        strSQL += Str(ParentId) & ", "
        strSQL += "'" & MyName & "'" & ", "
        strSQL += "0" & ");"

        '==> Execute SQL Query

        Dim xNumAffected As Int32
        Dim GpDcConnStr As String
        GpDcConnStr = ModMain.GpDcConnStr

        Dim cn As New SqlClient.SqlConnection(GpDcConnStr)
            Dim cmd As New SqlClient.SqlCommand(strSQL, cn)
            ' debug ..Console.WriteLine("strsql ==>" & strSQL & "<==")
            xNumAffected = cmd.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox("Error (111) Cannot Append TreeNodes to DataBase", MsgBoxStyle.Exclamation, "Database Error")
        End Try

        Dim child As TreeNode
        For Each child In Node.Nodes
            Call SaveRecursive(child)
    End Sub

By commenting out the lines of code in question the database
fields show as follows:  
TreeView in Database:

TvNodeId     TvParentId     TvNodeName  TvPermission      
  0                  0              Root           0
  1                        0              Sub1           0
  3                        0              Sub1a         0
  2                        0              Sub2           0
  4                        0              Sub2a         0
  5                        0              Sub2b         0
Question by:bulrick
    LVL 6

    Accepted Solution

    Without analyzing all of your code, this is what jumped out at me:

           Dim ParentId As New Integer

    Try removing the New keyword from that line (and won't you weep if that solves the problem!)

    LVL 10

    Expert Comment

    As ctm5 pointed out - the new could be the issue

    another way is to send it the parentId in each recursive call

    Private Sub SaveRecursive(ByVal Node As TreeNode, ByVal ParentId As Integer)

    ' Take out the if statement

    ' In your function
    SaveRecursive(child, MyId)

    ' In your main procedure
    SaveRecursive(xNode, 0)   ' Where 0 as a parentID defines that it is a root node



    Author Comment

    Thank you.... removing the 'New' solved the problem....  

        Somehow I was overlooked the small stuff.... but... finally I can move on...


    Featured Post

    How to improve team productivity

    Quip adds documents, spreadsheets, and tasklists to your Slack experience
    - Elevate ideas to Quip docs
    - Share Quip docs in Slack
    - Get notified of changes to your docs
    - Available on iOS/Android/Desktop/Web
    - Online/Offline

    Join & Write a Comment

    This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
    A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…

    733 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now