cydi
cydi

Reputation: 67

Object reference isn't set to an instance of an object

The error is in this image:

Error Message

How do I fix this?

My code:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim con As New MySqlConnection("host=localhost; username=root; database= login")
    Dim cmd As MySqlCommand
    Dim dr As MySqlDataReader

    con.Open()
    cmd.Connection = con 'this is where I have an error

    cmd.CommandText = "select userID, password from login where userID= ' " & userIDtxt.Text & " ' and password = ' " & pwTxt.Text & " '"
    dr = cmd.ExecuteReader

    If dr.HasRows Then
        MsgBox("Login successful!")
        Me.Hide()
        MainForm.Show()
    Else
        MsgBox("Username or password does not match")
        userIDtxt.Text = ""
        pwTxt.Text = " "
    End If

End Sub
End Class

Upvotes: 1

Views: 198

Answers (2)

Visual Vincent
Visual Vincent

Reputation: 18310

You haven't initialized a new instance of your cmd variable.

Change:

Dim cmd As MySqlCommand

to:

Dim cmd As New MySqlCommand

Upvotes: 0

Gouda Elalfy
Gouda Elalfy

Reputation: 7023

your sql connection string missing true credentials, this sample to connect to mysql with vb and c#:

https://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-open.html

Upvotes: 1

Related Questions