how to pass a data from a table in sql to a label even if the table is empty in visual basic

0

I have this code to pass the data:

   Using Conn As New SqlConnection("Data Source=SAMUELSUSANA; Initial catalog=poovb;integrated security=true")
        Conn.Open()
        Dim ConsultaSQL = "SELECT TOP 1 Codigo_venta FROM tblventas ORDER BY Codigo_venta DESC"
        lblcodigo.Text = New SqlCommand(ConsultaSQL, Conn).ExecuteScalar().ToString()
    End Using
  

If my table has at least one code, a sale works, but if it does not, it throws this error: Object reference not established as an instance of an object.

    
asked by Samuel Ignacio Susana Confesor 03.08.2017 в 00:42
source

1 answer

0

The problem occurs because the function ExecuteScalar() returns a null and that at the time of performing ToString throws the error.

As mentioned, you only need to validate that the value you get is not null before converting it to a string and then assign it to your Label lblcodigo.

lblcodigo.Text = ""

Using Conn As New SqlConnection("Data Source=SAMUELSUSANA; Initial catalog=poovb;integrated security=true")
    Conn.Open()
    Dim ConsultaSQL = "SELECT TOP 1 Codigo_venta FROM tblventas ORDER BY Codigo_venta DESC"

    Dim Resultado = New SqlCommand(ConsultaSQL, Conn).ExecuteScalar()
    If Not Resultado = Nothing Then
        lblcodigo.Text = Resultado.ToString
    End If

End Using

Reference:

answered by 03.08.2017 в 01:56