Object reference not set to an instance of an object?

0

I am connecting to the database and calling a procedure to insert in the database but this error occurs you know the reason:

Code:

Dim con As SqlConnection = New SqlConnection()
Dim cmd As SqlCommand = New SqlCommand()

con = Nothing
cmd = Nothing

Try

    con.ConnectionString = "Server = ;Database=;User Id=;Password = ;"

    con.Open()
    cmd.Connection = con
    cmd = New SqlCommand("prdInserirRegistro", con)
    cmd.CommandType = CommandType.StoredProcedure

    cmd.Parameters.Add(New SqlParameter("@dtLog", SqlDbType.DateTime))
    cmd.Parameters.Add(New SqlParameter("@dsLog", SqlDbType.VarChar, 1000))

    'recebe o parâmetro selecionado na combobox
    cmd.Parameters("@dtLog").Value = Now
    cmd.Parameters("@dsLog").Value = txtBoxLog.Text


    cmd.ExecuteNonQuery()

Catch ex As Exception
    MsgBox("erro em: " & ex.Message)
Finally

    If Not con Is Nothing Then
        con.Close()
        con.Dispose()
    End If
    con = Nothing

    If Not cmd Is Nothing Then
        cmd.Dispose()
    End If
    cmd = Nothing
    
asked by anonymous 24.02.2017 / 18:10

2 answers

1

Your code is in this order:

  • Dim cmd As SqlCommand = New SqlCommand()

  • cmd = Nothing

  • cmd.Connection = con

  • Dim con As SqlConnection = New SqlConnection()

  • con = Nothing

  • con.ConnectionString = "Server = ;Database=;User Id=;Password = ;"

  • In the second step you assign con and cmd to Nothing .

    Therefore, the references they had to instances of the classes created in step 1 are lost.

    Remove excerpts from item 2 ( con = Nothing and cmd = Nothing )

        
    24.02.2017 / 18:34
    1

    You have to remove this con = Nothing . In fact the code is pretty confusing, doing nonsense things, it might be that solving this error find others.

    Dim con As SqlConnection = New SqlConnection() //criou o objeto
    Dim cmd As SqlCommand = New SqlCommand()
    con = Nothing // ===============================>abandonou objeto
    cmd = Nothing
    Try
        //Aqui teneta acessar o objeto que não existe, por isso dá esse erro
        con.ConnectionString = "Server = ;Database=;User Id=;Password = ;"
    
        
    24.02.2017 / 18:33