0

My database has a table called "SerialKey" 3 columns id which is PK Email & Serial.

I have a windows form in VB.NET, the form has 1 label, 1 TextBox, 1 Button, The text in the label displays an email address, this email address will vary. When I click the button on the form I want the database to be searched for the email address and find the serial in the database. I have shown the code below but it gives me an error saying "Object reference not set to an instance of an object" it highlights the line below.

Dim reader As SqlDataReader = command.ExecuteReader()

Can someone help me out here because I'm truly stuck and truly new :) Any help appreciated.

con = New SqlConnection("Data Source= My connection string here; Password='my password here'; ")
    cmd.Connection = con
        cmd.CommandText = "SELECT Serial FROM SerialKey Where Serial= ?"
        cmd.Parameters.AddWithValue("?", LblName.Text)
        con.Open()
        Dim lrd As SqlDataReader = cmd.ExecuteReader()
        While lrd.Read()
            'Do something
            If lrd.HasRows Then
                lrd.Read()
                UsersKey.Text = lrd.GetString(1)               
                TextBox2.Text = lrd.GetString(2)
            End If
        End While
    Catch ex As Exception
        MessageBox.Show("Error while retrieving records on table..." & ex.Message, "Load Records")
    Finally
        con.Close()
    End Try
  • what is the use of cmd if you're using command.ExecuteReader()?? – Sushil Jun 02 '15 at 21:15
  • I don't see any declaration for `cmd` or `command`. Your `command` should probably be `cmd` since that is what you are working with prior and probably is initialized since you did not get a null reference on `cmd.Connection` – TyCobb Jun 02 '15 at 21:15
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – TyCobb Jun 02 '15 at 21:17
  • Since you say are very new I would offer a couple of suggestions. First, move your connection information to your config file. This minimizes the pain when it needs to change. Also, you should read this article about AddWithValue. http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ – Sean Lange Jun 02 '15 at 21:18
  • Hi TyCobb, I did declare I used Dim cmd As New SqlCommand and this is not a duplicate post. – user3335985 Jun 05 '15 at 09:54
  • Hi Sushil, "what is the use of cmd if you're using command.ExecuteReader()??" How am I supposed to know this if I am new to it unfortunately as fast as I would like to learn it I cant it takes time. Their is nothing to stop you helping me out and getting past this problem I have. I'm sure if I could get a good solid example to work off I would be OK. – user3335985 Jun 05 '15 at 09:57

0 Answers0