Object reference not set to an instance of an object,

Hi,
I have this error message "Object reference not set to an instance of an object" when i push button on form and call Private Sub Save_Click...
Short description of code flow:
1. I'm loading my treeview by filling dataadapter with data from SQL Server DB
2. I have created drag and drop - works OK
3.After i drag n drop I want to push my button in order to save my changes in DB (Private Sub Save_Click) - on this event i pop-up with this error massage

Please can somebody help me and go through my code just for review if everithing is Ok and to give me possible further instructions how to solve my problem...

my table structure as follows:

ID      float      
TCID      nvarchar(255)      
TCID_name      nvarchar(255)
Reports      float
NodePictureNormal      nvarchar(255)      
NodePictureNormal1      int      
HID      nvarchar(MAX)      
            

thanks....
Imports System.Data.SqlClient

Public Class Form1
    Private con As New SqlConnection()

    Private WithEvents cmdSelectAuthor As New SqlCommand()
    Private WithEvents cmdInsertAuthor As New SqlCommand()
    Private WithEvents cmdUpdateAuthor As New SqlCommand()
    Private WithEvents cmdDeleteAuthor As New SqlCommand()

    Private WithEvents daTreeView As New SqlDataAdapter()

    Private WithEvents dsTreeView As New DataSet()
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        con.ConnectionString = "Data Source=S_A-PC\SQLEXPRESS1;Initial Catalog=AdventureWorks;Integrated Security=True"
        con.Open()
        Dim cmd As SqlCommand = New SqlCommand()


        daTreeView.SelectCommand = cmdSelectAuthor
        daTreeView.InsertCommand = cmdInsertAuthor
        daTreeView.UpdateCommand = cmdUpdateAuthor
        daTreeView.DeleteCommand = cmdDeleteAuthor



        daTreeView.UpdateCommand.CommandText = "UPDATE CostC1 SET ID = @ID, TCID = @TCID, TCID_name= @TCID_name, Reports = @Reports, NodePictureNormal = @NodePictureNormal, NodePictureNormal1 = @NodePictureNormal1, HID = @contract WHERE ID = @HID"
        daTreeView.UpdateCommand.Connection = con

        daTreeView.UpdateCommand.Parameters.Add("@ID", SqlDbType.Float)
        daTreeView.UpdateCommand.Parameters("@ID").Value = "ID"
        daTreeView.UpdateCommand.Parameters.Add("@TCID", SqlDbType.NVarChar, 255, "TCID")
        daTreeView.UpdateCommand.Parameters.Add("@TCID_name", SqlDbType.NVarChar, 255, "TCID_name")
        daTreeView.UpdateCommand.Parameters.Add("@Reports", SqlDbType.Float)
        daTreeView.UpdateCommand.Parameters("@Reports").Value = "Reports"
        daTreeView.UpdateCommand.Parameters.Add("@NodePictureNormal", SqlDbType.NVarChar, 255, "NodePictureNormal")
        daTreeView.UpdateCommand.Parameters.Add("@NodePictureNormal1", SqlDbType.Int)
        daTreeView.UpdateCommand.Parameters("@NodePictureNormal1").Value = "NodePictureNormal1"
        daTreeView.UpdateCommand.Parameters.Add("@HID", SqlDbType.NVarChar, 255, "HID")


        daTreeView.DeleteCommand.CommandText = "DELETE FROM CostC1 WHERE ID = @ID"
        daTreeView.DeleteCommand.Connection = con
        daTreeView.DeleteCommand.Parameters.Add("@ID", SqlDbType.Float)
        daTreeView.DeleteCommand.Parameters("@ID").Value = "ID"

        daTreeView.InsertCommand.CommandText = "INSERT INTO authors (ID, TCID, TCID_name, Reports, NodePictureNormal, NodePictureNormal1, HID) VALUES (@ID,@TCID,@TCID_name,@Reports,@NodePictureNormal,@NodePictureNormal1,@HID)"
        daTreeView.InsertCommand.Connection = con
        daTreeView.InsertCommand.Parameters.Add("@ID", SqlDbType.Float)
        daTreeView.InsertCommand.Parameters("@ID").Value = "ID"
        daTreeView.InsertCommand.Parameters.Add("@TCID", SqlDbType.NVarChar, 255, "TCID")
        daTreeView.InsertCommand.Parameters.Add("@TCID_name", SqlDbType.NVarChar, 255, "TCID_name")
        daTreeView.InsertCommand.Parameters.Add("@Reports", SqlDbType.Float)
        daTreeView.InsertCommand.Parameters("@Reports").Value = "Reports"
        daTreeView.InsertCommand.Parameters.Add("@NodePictureNormal", SqlDbType.NVarChar, 255, "NodePictureNormal")
        daTreeView.InsertCommand.Parameters.Add("@NodePictureNormal1", SqlDbType.Int)
        daTreeView.InsertCommand.Parameters("@NodePictureNormal1").Value = "NodePictureNormal1"
        daTreeView.InsertCommand.Parameters.Add("@HID", SqlDbType.NVarChar, 255, "HID")


        cmd.CommandType = CommandType.Text
        cmd.CommandText = "SELECT DISTINCT HID FROM CostC1"
        cmd.Connection = con

        Dim dr As SqlDataReader
        Dim i As Integer

        dr = cmd.ExecuteReader(CommandBehavior.Default)
        Do While dr.Read
            i = ComboBox1.Items.Add(dr("HID"))
        Loop
        con.Close()
    End Sub

' here loading my treeview.....

' code for drag and drop.....

Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click


     
        Try
            daTreeView.Update(dsTreeView.Tables("CostC1"))

        Catch ex As Exception
            MsgBox(ex.Message)
            MsgBox(ex.ToString)


        End Try
    End Sub

Open in new window

LVL 1
alsamAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

13598Commented:
What happens if you use just:
 daTreeView.Update(dsTreeView)
0
shadow77Commented:
In the code you provided, you never put anything into dsTreeView; you just create the object but never change it.

If you don't do that somewhere, there will be no CostC1 (or any other) table in dsTreeView and dsTreeView.Tables("CostC1") will return Nothing, which is what the error message is telling you.
0
alsamAuthor Commented:
OK
Here is complete code
I'm not sure about this not puttin into dsTreeView
Can you now review my whole code....

Again breaks on   daTreeView.Update(dsTreeView.Tables("CostC1"))



Imports System.Data.SqlClient

Public Class Form1
    Private con As New SqlConnection()

    Private WithEvents cmdSelectAuthor As New SqlCommand()
    Private WithEvents cmdInsertAuthor As New SqlCommand()
    Private WithEvents cmdUpdateAuthor As New SqlCommand()
    Private WithEvents cmdDeleteAuthor As New SqlCommand()

    Private WithEvents daTreeView As New SqlDataAdapter()

    Private WithEvents dsTreeView As New DataSet()
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        con.ConnectionString = "Data Source=S_A-PC\SQLEXPRESS1;Initial Catalog=AdventureWorks;Integrated Security=True"
        con.Open()
        Dim cmd As SqlCommand = New SqlCommand()


        daTreeView.SelectCommand = cmdSelectAuthor
        daTreeView.InsertCommand = cmdInsertAuthor
        daTreeView.UpdateCommand = cmdUpdateAuthor
        daTreeView.DeleteCommand = cmdDeleteAuthor



        daTreeView.UpdateCommand.CommandText = "UPDATE CostC1 SET ID = @ID, TCID = @TCID, TCID_name= @TCID_name, Reports = @Reports, NodePictureNormal = @NodePictureNormal, NodePictureNormal1 = @NodePictureNormal1, HID = @contract WHERE ID = @HID"
        daTreeView.UpdateCommand.Connection = con

        daTreeView.UpdateCommand.Parameters.Add("@ID", SqlDbType.Float)
        daTreeView.UpdateCommand.Parameters("@ID").Value = "ID"
        daTreeView.UpdateCommand.Parameters.Add("@TCID", SqlDbType.NVarChar, 255, "TCID")
        daTreeView.UpdateCommand.Parameters.Add("@TCID_name", SqlDbType.NVarChar, 255, "TCID_name")
        daTreeView.UpdateCommand.Parameters.Add("@Reports", SqlDbType.Float)
        daTreeView.UpdateCommand.Parameters("@Reports").Value = "Reports"
        daTreeView.UpdateCommand.Parameters.Add("@NodePictureNormal", SqlDbType.NVarChar, 255, "NodePictureNormal")
        daTreeView.UpdateCommand.Parameters.Add("@NodePictureNormal1", SqlDbType.Int)
        daTreeView.UpdateCommand.Parameters("@NodePictureNormal1").Value = "NodePictureNormal1"
        daTreeView.UpdateCommand.Parameters.Add("@HID", SqlDbType.NVarChar, 255, "HID")


        daTreeView.DeleteCommand.CommandText = "DELETE FROM CostC1 WHERE ID = @ID"
        daTreeView.DeleteCommand.Connection = con
        daTreeView.DeleteCommand.Parameters.Add("@ID", SqlDbType.Float)
        daTreeView.DeleteCommand.Parameters("@ID").Value = "ID"

        daTreeView.InsertCommand.CommandText = "INSERT INTO authors (ID, TCID, TCID_name, Reports, NodePictureNormal, NodePictureNormal1, HID) VALUES (@ID,@TCID,@TCID_name,@Reports,@NodePictureNormal,@NodePictureNormal1,@HID)"
        daTreeView.InsertCommand.Connection = con
        daTreeView.InsertCommand.Parameters.Add("@ID", SqlDbType.Float)
        daTreeView.InsertCommand.Parameters("@ID").Value = "ID"
        daTreeView.InsertCommand.Parameters.Add("@TCID", SqlDbType.NVarChar, 255, "TCID")
        daTreeView.InsertCommand.Parameters.Add("@TCID_name", SqlDbType.NVarChar, 255, "TCID_name")
        daTreeView.InsertCommand.Parameters.Add("@Reports", SqlDbType.Float)
        daTreeView.InsertCommand.Parameters("@Reports").Value = "Reports"
        daTreeView.InsertCommand.Parameters.Add("@NodePictureNormal", SqlDbType.NVarChar, 255, "NodePictureNormal")
        daTreeView.InsertCommand.Parameters.Add("@NodePictureNormal1", SqlDbType.Int)
        daTreeView.InsertCommand.Parameters("@NodePictureNormal1").Value = "NodePictureNormal1"
        daTreeView.InsertCommand.Parameters.Add("@HID", SqlDbType.NVarChar, 255, "HID")


        cmd.CommandType = CommandType.Text
        cmd.CommandText = "SELECT DISTINCT HID FROM CostC1"
        cmd.Connection = con

        Dim dr As SqlDataReader
        Dim i As Integer

        dr = cmd.ExecuteReader(CommandBehavior.Default)
        Do While dr.Read
            i = ComboBox1.Items.Add(dr("HID"))
        Loop
        con.Close()
    End Sub

    

    Private Sub Rootnode(ByVal param As String)
        TreeView1.Nodes.Clear()
        con.ConnectionString = "Data Source=S_A-PC\SQLEXPRESS1;Initial Catalog=AdventureWorks;Integrated Security=True"
        con.Open()
       
        daTreeView.SelectCommand.CommandText = "SELECT * FROM CostC1 WHERE HID = @param"
        daTreeView.SelectCommand.Parameters.Add("@param", SqlDbType.NVarChar)
        daTreeView.SelectCommand.Parameters("@param").Value = param
        daTreeView.SelectCommand.Connection = con



        
        daTreeView.Fill(dsTreeView, "dtCosts1")
        con.Close()


        dsTreeView.Relations.Add("Parenttochild", dsTreeView.Tables("dtCosts1").Columns("ID"), dsTreeView.Tables("dtCosts1").Columns("Reports"), False)

        LoadTreeView(dsTreeView)
        TreeView1.CollapseAll()

    End Sub


    Private Sub LoadTreeView(ByVal DSNWind As DataSet)
        Dim oTreeView As TreeView = New TreeView()
        Dim oDataRow As DataRow
        oTreeView = Me.TreeView1

        For Each oDataRow In dsTreeView.Tables("dtCosts1").Rows
            ' pronalazi Root node, node koji ima vrijednost NULL
            If oDataRow.IsNull("Reports") Then

                Dim oNode As New System.Windows.Forms.TreeNode
                oNode.Tag() = oDataRow("ID")
                oNode.ImageIndex = oDataRow("NodePictureNormal")
                oNode.SelectedImageIndex() = CType(oDataRow.Item("NodePictureNormal"), Integer)
                oNode.Text = oDataRow("TCID") & (" " + oDataRow("TCID_name").ToString())
                oTreeView.Nodes.Add(oNode)

                'Popuni od definisanog roota
                RecursivelyLoadTree(oDataRow, oNode)
            End If
        Next oDataRow
        Controls.Add(oTreeView)

        dsTreeView.Dispose()
        dsTreeView = Nothing

    End Sub

    Private Sub RecursivelyLoadTree(ByVal oDataRow As DataRow, _
   ByRef oNode As TreeNode)
        Dim oChildRow As DataRow

        For Each oChildRow In oDataRow.GetChildRows("Parenttochild")

            Dim oChildNode As New TreeNode()
            oChildNode.Tag = oChildRow("ID")
            oChildNode.Text = oChildRow("TCID") & (" " + oChildRow("TCID_name").ToString())
            oChildNode.ImageIndex() = oDataRow("NodePictureNormal")
            oChildNode.SelectedImageIndex() = CType(oDataRow.Item("NodePictureNormal"), Integer)
            oNode.Nodes.Add(oChildNode)

            RecursivelyLoadTree(oChildRow, oChildNode)
        Next oChildRow


    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        Call Rootnode(Me.ComboBox1.Text)
    End Sub

    Public Sub TreeView1_ItemDrag(ByVal sender As System.Object, _
        ByVal e As System.Windows.Forms.ItemDragEventArgs) _
        Handles TreeView1.ItemDrag


        DoDragDrop(e.Item, DragDropEffects.Move)

    End Sub

    Public Sub TreeView1_DragEnter(ByVal sender As System.Object, _
        ByVal e As System.Windows.Forms.DragEventArgs) _
        Handles TreeView1.DragEnter


        If e.Data.GetDataPresent("System.Windows.Forms.TreeNode", _
            True) Then

            e.Effect = DragDropEffects.Move
        Else

            e.Effect = DragDropEffects.None
        End If

    End Sub

    Public Sub TreeView1_DragOver(ByVal sender As System.Object, _
         ByVal e As System.Windows.Forms.DragEventArgs) _
        Handles TreeView1.DragOver


        If e.Data.GetDataPresent("System.Windows.Forms.TreeNode", _
               True) = False Then Exit Sub


        Dim selectedTreeview As TreeView = CType(sender, TreeView)

 
        Dim pt As Point = _
            CType(sender, TreeView).PointToClient(New Point(e.X, e.Y))
        Dim targetNode As TreeNode = selectedTreeview.GetNodeAt(pt)

   
        If Not (selectedTreeview.SelectedNode Is targetNode) Then

            selectedTreeview.SelectedNode = targetNode

         
            Dim dropNode As TreeNode = _
                CType(e.Data.GetData("System.Windows.Forms.TreeNode"),  _
                TreeNode)

            Do Until targetNode Is Nothing
                If targetNode Is dropNode Then
                    e.Effect = DragDropEffects.None
                    Exit Sub
                End If
                targetNode = targetNode.Parent
            Loop
        End If


        e.Effect = DragDropEffects.Move


    End Sub

    Public Sub TreeView1_DragDrop(ByVal sender As System.Object, _
       ByVal e As System.Windows.Forms.DragEventArgs) _
       Handles TreeView1.DragDrop



        If e.Data.GetDataPresent("System.Windows.Forms.TreeNode", _
              True) = False Then Exit Sub


        Dim selectedTreeview As TreeView = CType(sender, TreeView)


        Dim dropNode As TreeNode = _
              CType(e.Data.GetData("System.Windows.Forms.TreeNode"),  _
              TreeNode)


        Dim targetNode As TreeNode = selectedTreeview.SelectedNode


        dropNode.Remove()

        
        If targetNode Is Nothing Then
            selectedTreeview.Nodes.Add(dropNode)
        Else
            targetNode.Nodes.Add(dropNode)

            

      

        End If



        dropNode.EnsureVisible()
        selectedTreeview.SelectedNode = dropNode

    End Sub


    Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click


     
        Try
            daTreeView.Update(dsTreeView.Tables("CostC1"))

        Catch ex As Exception
            MsgBox(ex.Message)
            MsgBox(ex.ToString)


        End Try
    End Sub
End Class

Open in new window

0
Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

shadow77Commented:
If you search through your code for dsTreeView, you will find several references to "dtCosts1".  Maybe this means the line that fails
    daTreeView.Update(dsTreeView.Tables("CostC1"))
should be
    daTreeView.Update(dsTreeView.Tables("dtCosts1"))

If not, you need to look at your data to see which tables are present because "CostC1" is not in your DataSet dsTreeView when you enter your Save_Click sub.
0
shadow77Commented:
You might try replacing
    daTreeView.Update(dsTreeView.Tables("CostC1"))
with
    DataTable table = dsTreeView.Tables("CostC1")
    if table isnot Nothing Then daTreeView.Update(table)

That would eliminate your error mesage.
0
alsamAuthor Commented:
Ok
thank you for your reply.
I changed my line into daTreeView.Update(dsTreeView.Tables("dtCosts1"))
Even though I misspeled my dataset name this solution still does not work,.
I have the same message again
Also I tried your last posted solution - still nothig - same error message again...
Please any further idea...


0
shadow77Commented:
I'm surprised the last suggestion did not help.

Rewrite Save_Click as follows.  What messages do you get now?
Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click
    Try
        If daTreeView is Nothing Then
            MsgBox("daTreeView is Nothing", MsgBoxStyle.OkOnly, "Save_Click")
        ElseIf dsTreeView is Nothing Then
            MsgBox("dsTreeView is Nothing", MsgBoxStyle.OkOnly, "Save_Click")
        Else
            DataTable table = dsTreeView.Tables("CostC1")
            If table Is Nothing Then
                MsgBox("table is Nothing", MsgBoxStyle.OkOnly, "Save_Click")
            Else
                daTreeView.Update(table)
            Endif
        Endif
    Catch ex As Exception
        MsgBox(ex.Message)
        MsgBox(ex.ToString)
    End Try
End Sub

Open in new window

0
alsamAuthor Commented:
Hi again,
sorry for delay .....
I set your logical test and receive "dsTreeView is Nothing" message....
Do you have any idea how to solve the problem with this....
Thank you  once more for your time and effort...

Kind regards

0
shadow77Commented:
Hi,

Search through your program for dsTreeView.

In line 13, it is declared as a class member and initialized to an empty DataSet.  It is not Nothing at this point, but it contains no data.

In line 91, it is filled from "dtCosts1".

In line 95, a relation is added.

In line 97, it is passed to LoadTreeView.

LoadTreeView receives dsTreeView as a parameter.
Note that the parameter is never used; instead, LoadTreeView uses dsTreeView directly.
Before it exits, LoadTreeView destroys dsTreeView (lines 125-6).
        dsTreeView.Dispose()
        dsTreeView = Nothing
This is why dsTreeView is Nothing when you reach Save_Click.

In Save_Click, I suggest you keep the logic I sent earlier (that tests for Nothing).
You may also want to use "dtCosts1" in place of "CostsC1" since that is what you use elsewhere.

I suggest that you disable the Save button until you fill dsTreeView with data.  You should also disable it when you empty dsTreeView or Dispose of it.  That way the user can't click Save, and you won't enter that module, unless there is something in dsTreeView.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
alsamAuthor Commented:
Hi,
I m trying to follow your logic
So  
dsTreeView.Dispose()
        dsTreeView = Nothing
still remain as it is.....
Save button disabled - so far OK

I set my Save_click like

Try
            If daTreeView Is Nothing Then
                MsgBox("daTreeView is Nothing", MsgBoxStyle.OkOnly, "Save_Click")
            ElseIf dsTreeView Is Nothing Then
                MsgBox("dsTreeView is Nothing", MsgBoxStyle.OkOnly, "Save_Click")
            Else
                daTreeView.Update(dsTreeView.Tables("dtCosts1"))
            End If

        Catch ex As Exception
            MsgBox(ex.Message)
            MsgBox(ex.ToString)
        End Try

How to load my dataset again after drag and drop and in which part of my code...
Please advise


0
shadow77Commented:
Hi,

No, I wasn't necessarily recommending that you leave those two lines as they are.  I just said that they were the reason you were seeing your original "Object reference not set..."message.  After executing those two statements, dsTreeView no longer refers to an object.

I was trying to answer your original question.

I'm sorry, but I don't have the time necessary to fully understand what your program is doing.  I have shown you where your message is coming from, but I can't really advise you on how to reorganize your program.  Also, because I don't have your data or your form designs, I'm not in a position to run the program to see what you're doing.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.