0

I want to save data from textbox1 and textbox2 to database, but i get this error and the error do not mention which line that the error occur. This is the error:

Object reference not set to an instance of an object.

 Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text = "" And TextBox2.Text = "" Then Exit Sub

    Try
        conn = New MySqlConnection
        conn.ConnectionString = connstr
        conn.Open()

        strsql = "INSERT INTO supplier "
        strsql += "(SupplierName,SupplierID) VALUES "
        strsql += "(@Name, @ID);"

        cmd.Connection = conn
        cmd.CommandText = strsql
        cmd.Parameters.AddWithValue("@Name", TextBox1.Text)
        cmd.Parameters.AddWithValue("@ID", TextBox2.Text)
        cmd.ExecuteNonQuery()
        cmd.Parameters.Clear()
        cmd.Dispose()

        conn.Close()
    Catch ex As Exception
        Response.Write(ex.Message)
    End Try
End Sub
hasni
  • 29
  • 8
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Izzy Jul 07 '17 at 08:13
  • Which line of code gives you error? Did you debug the code to see which line is breaking? You dont have `cmd = New MySqlCommand`. Looks like that's the issue. – Chetan Jul 07 '17 at 09:30
  • @Chetan Ranpariya Thanks. I already solve the problem with your answer. – hasni Jul 10 '17 at 03:36

1 Answers1

0

To get the error line simply remove (temporarily) the try / catch block

Stefano Losi
  • 719
  • 7
  • 18