0

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`
Steve
  • 213,761
  • 22
  • 232
  • 286
JellyAnne
  • 1
  • 3
  • After reading the duplicate, look carefully at your code. What object is nothing when you try to use it? – Steve Apr 09 '18 at 12:06
  • 1
    I cant answer as it has been marked as duplicate. I have written out your code corrected. The main issue is that you are calling for `Reader.Item(2)` which is essentially not there, you only have ONE colum in your select query (lastname) so you'll need to change to `reader.item(0)` column numbering is 0,1,2... _n_ . Are you trying to pull the data from the Second _Record_ or the second _Column_? Hopefully this helps, if you need the complete code I'll try and get it posted – Chicken Apr 09 '18 at 12:40

0 Answers0