Object Reference not set to an instance of an Object?

Asked

Viewed 87 times

0

I’m tapping into the database and calling a procedure to insert into the bank 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
  • What mistake happens?

  • On which line does the error occur? Where variables are declared con, conecta, comando, cmd? Good names to cause trouble.

  • this is the error :that occurs Object Reference not set to an instance of an Object the variables are declared above are like this: Dim con As Sqlconnection = New Sqlconnection() Dim cmd As Sqlcommand = New Sqlcommand() con = Nothing cmd = Nothing

2 answers

1

You gotta take that con = Nothing. In fact the code is very confused, doing nonsense things, it may be that solving this error find other.

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

I put in the Github for future reference.

1


Your code is in that order:

  1. Dim cmd As SqlCommand = New SqlCommand()

  2. cmd = Nothing

  3. cmd.Connection = con


  1. Dim con As SqlConnection = New SqlConnection()

  2. con = Nothing

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


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

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

Remove the snippets from item 2 (con = Nothing and cmd = Nothing)

  • 1

    thank you , it worked

  • Cool! I’m glad I helped. I updated the answer explaining a little better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.