I want to display information from my database as a label with the following code. But I always get an "Object reference not set to an instance of an object" error. Is my code correct? Or can you help me with a better code?
Imports MySql.Data.MySqlClient
Public Class dbtolabel
Dim Mysqlconn As MySqlConnection
Dim Command As MySqlCommand
Private Sub conn()
Mysqlconn = New MySqlConnection
Mysqlconn.ConnectionString = "server = localhost; userid = root; password = root; database = db_payroll"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
conn()
Try
Dim Reader As MySqlDataReader
Mysqlconn.Open()
Command.Connection = Mysqlconn
Command.CommandText = "select lastname from dbsample.tblemployees where barcode like '" & TextBox1.Text & "'"
Reader = Command.ExecuteReader()
If Reader.Read() Then
Label2.Text = Reader.Item(2).ToString
End If
Reader.Close()
Mysqlconn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class`