我希望使用以下代码将数据库中的信息显示为标签。但我总是得到一个"对象引用未设置为对象的实例"错误。我的代码是否正确?或者你可以用更好的代码帮助我吗?
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`