got error message 'Object reference not set to an instance of an object

Posted on 2005-04-20
Last Modified: 2007-12-19
I am trying to read all the nodes within a treeview in VB.NET, the tree structure is sort of like this:


The coding I am using is :
Private Sub RecurseNodes(ByVal col As TreeNodeCollection)
        For Each tn As TreeNode In col

            'If tn.Nodes.Contains(tn) = True Then
            If (tn.IsExpanded And tn.Nodes.Count > 0) Or (Not tn.IsExpanded And tn.Nodes.Count = 0 And tn.PrevVisibleNode.Text = "") Then
                gaORU(o, r, u) = tn.Text + ", NULL" + ", NULL"
                gaORU(o, r, u) = "NULL, " + tn.Text + ", NULL"
            End If
        Next tn
    End Sub

  Private Sub Test()
    End Sub

The error message pop up when the line read the line of tn.PrevVisibleNode.text, anyone knows how to solve this problem, read the first node of 'xxx' no problem, only when it reads the second node 'aaa', the reason I did this is trying to build up an array, which I can use the data inside the array for stored procedure to save the treeview nodes data into the SQL table?

I seached MSDN and google, just can't find any sample as far as how to save the treeview nodes data directly into SQL table, most samples are to save treeview nodes into XML file, I would assume it should be used as a bridge to save XML data into SQL table, anyone has any suggestions? Thank you in advance.
Question by:cocoWang
    LVL 10

    Accepted Solution

    It looks like the reason this happens is because when you do the check tn.PrevVisible is equal to "Nothing, " or "null" in other languages. You can't use an object's properties if it is null. You may want to write your check like this:

    If (tn.IsExpanded And tn.Nodes.Count > 0) Or (Not tn.IsExpanded And tn.Nodes.Count = 0 And tn.PrevVisibleNode Is Nothing)

    Also, if I do recursive calls like that I make the method signature take in parameters ByRef.

    Author Comment

    It works by changing the ByVal to ByRef and tn.PrevVisibleNode.text = "" to tn.Parent is nothing. Thank you very mucy.
    Do you know how to save treeview nodes data back to SQL table?, I did some coding as below to display nodes from SQL tables.

    g_oTv = TreeView3
            Dim myConnString As String = _
                "Data Source=(local);Initial Catalog=MedlogixNET;Integrated Security=SSPI;"
            '"Data Source=PAR-SQL1,1433;Initial Catalog=ScratchDB;Integrated Security=SSPI;"

            Dim CN As SqlConnection = Connect(myConnString)
            Dim DAORg As New SqlClient.SqlDataAdapter("SELECT * FROM WFOrg ", CN)

            Dim DAWFRole As New SqlClient.SqlDataAdapter("SELECT WFRoleID, Description  From WFRole ", CN)

            Dim DARole As New SqlClient.SqlDataAdapter("select R.Description,OrgRole.WFRoleID, " & _
                " WFOrgID from WFOrgRole as OrgRole inner join WFRole as R " & _
                " on OrgRole.WFRoleID = R.WFRoleID Where WForgID in (Select WFOrgID from WFOrg)", CN)

            Dim DAUser As New SqlClient.SqlDataAdapter("select U.NameFirst + ' ' + U.Namelast, " & _
                " M.WFRoleID from MLUser as U inner join WFOrgRoleUser as M on U.MLUserID = M.MLUserID " & _
                " where WFRoleID in (select WFRoleID from WFOrgRole where WFOrgID " & _
                " in(Select WFOrgID from WFOrg)) order by U.NameFirst + ' ' + U.Namelast", CN)

            Dim DAUserRole As New SqlClient.SqlDataAdapter("Select ORU.WFRoleID, U.NameFirst + ' ' + U.Namelast " & _
                " FROM MLUser as U inner join WFOrgRoleUser as ORU on U.MLUserID = " & _
                " ORU.MLUSerID where WFRoleID in (Select WFRoleID from WFRole )", CN)

            DAORg.Fill(dset, "dtOrg")
            DAWFRole.Fill(dset, "dtWFRole")
            DARole.Fill(dset, "dtRole")
            DAUser.Fill(dset, "dtUser")
            DAUserRole.Fill(dset, "dtUserRole")

            'Create a data relation object to facilitate the relationship between the WFOrg, WFOrgRole and WFOrgRoleUser tables.
            dset.Relations.Add("OrgToRole", dset.Tables("dtOrg").Columns("WFOrgID"), dset.Tables("dtRole").Columns("WFOrgID"))
            dset.Relations.Add("RoleToUser", dset.Tables("dtRole").Columns("WFRoleID"), dset.Tables("dtUser").Columns("WFRoleID"))
            dset.Relations.Add("UserToWFRole", dset.Tables("dtWFRole").Columns("WFRoleID"), dset.Tables("dtUserRole").Columns("WFRoleID"))
            Dim parentrow As DataRow
            Dim ParentTable As DataTable
            Dim ChildTable As DataTable
            ParentTable = dset.Tables("dtOrg")

            For Each parentrow In ParentTable.Rows
                Dim parentnode As TreeNode
                parentnode = New TreeNode(parentrow.Item(1))
                Dim childrow As DataRow
                Dim childnode As TreeNode
                childnode = New TreeNode
                For Each childrow In parentrow.GetChildRows("OrgToRole")
                    childnode = parentnode.Nodes.Add(childrow(0))
                    childnode.Tag = childrow("WFRoleID")
                    Dim childrow2 As DataRow
                    Dim childnode2 As TreeNode
                    childnode2 = New TreeNode
                    For Each childrow2 In childrow.GetChildRows("RoleToUser")
                        childnode2 = childnode.Nodes.Add(childrow2(0))
                    Next childrow2
                Next childrow
            Next parentrow
            ChildTable = dset.Tables("dtRole")
            For Each parentrow In ChildTable.Rows
                Dim parentnode As TreeNode
                parentnode = New TreeNode(parentrow(0))
                Dim childrow As DataRow
                Dim childnode As TreeNode
                childnode = New TreeNode
                For Each childrow In parentrow.GetChildRows("RoleToUser")
                    childnode = parentnode.Nodes.Add(childrow(0))
                    childnode.Tag = childrow("WFRoleID")
                Next childrow
            Next parentrow

            ChildTable = dset.Tables("dtUserRole")
            For Each parentrow In ChildTable.Rows
                Dim parentnode As TreeNode
                parentnode = New TreeNode(parentrow(1))
                Dim childrow As DataRow
                Dim childnode2 As TreeNode
                childnode2 = New TreeNode
                For Each childrow In parentrow.GetChildRows("UserToWFRole")
                    childnode2 = parentnode.Nodes.Add(childrow(0))
                    childnode2.Tag = childrow("WFRoleID")
                Next childrow
            Next parentrow

    Tried search for quite a long time for anyone who did the save from treeview to table, I found zero sample, what will you do to so the saving after you add, edit and delete various number of nodes?
    LVL 10

    Expert Comment

    Well this is a seperate question. But ok, why not just add, remove, update the records in the database whenever they are actually changed in the treeview with plain old SQL and commandtext (or stored procedures if you like). There may be a more elegant solution but that is the most straight forward. So whenever you do an add operation in TreeView, do the appropriate "INSERT INTO" statement for your database, and the same sort of thing for UPDATE and DELETE. Since I see you doing inner joins, I'm sure you are well versed in that! =)  Or is there some reason why this method won't work for you? Possibly I am misunderstanding the question.
    LVL 44

    Expert Comment

    you might also try this variant:

    If (tn.IsExpanded AndAlso tn.Nodes.Count > 0) OrElse (Not tn.IsExpanded AndAlso tn.Nodes.Count = 0 AndAlso tn.PrevVisibleNode Is Nothing)

    this will allow 'short-circuiting' of the If tests, and may avoid the situation altogether.


    Author Comment


    Yes, it is a separate question, but I included it on the original question, that is why I gave 500 points in the first place.  This is a more tougher question, because there are three treeviews, which the data of each treeview nodes were loaded from 5 tables, and user can do add,edit and delete functions on nodes from two treeviews and save the data back to the 5 tables after all changes are done.

    I have the idea of using multi-dimentional array to store the original data when I load the form, after all add, edit and delete functions are done, scan each treeview and create another multi-dimentional array, compare which nodes were added as new, which were edited,and which were deleted, flag for deletion, and decide how to save the new data back to those 5 tables.

    Please advise if you have different point of view or idea.

    Thank you very much for your help

    Author Comment


    Since I did not hear from you regarding my second question for a long time, I would like to close this case by now, and I think it is fair for give you a credit of 250 points for the answer you replied on 4/20/2005 if that is alright with you.


    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    Join & Write a Comment

    The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (…
    If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
    In this sixth video of the Xpdf series, we discuss and demonstrate the PDFtoPNG utility, which converts a multi-page PDF file to separate color, grayscale, or monochrome PNG files, creating one PNG file for each page in the PDF. It does this via a c…
    This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor ( If you're looking for how to monitor bandwidth using netflow or packet s…

    746 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

    15 Experts available now in Live!

    Get 1:1 Help Now