ASP.Net: Check if SqlDataReader has no rows using VB.Net

makumbi
 
on Jul 14, 2022 07:32 AM
426 Views

How I can modify this code in the reader to display message in case the table archivedmax does not have values in it

please help

Dim strConnString As String = ConfigurationManager.ConnectionStrings("SMIS2022ConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(strConnString)
    Using cmd As SqlCommand = New SqlCommand()
        cmd.CommandText = "SELECT * From Archivemax"
        ' cmd.Parameters.AddWithValue("@Id", ID)
        cmd.Connection = con
        con.Open()
        Dim sdr As SqlDataReader = cmd.ExecuteReader()
        sdr.Read()
        Monthed.Text = sdr("Month").ToString()
        Expr2.Text = sdr("Expressed").ToString()
        types2term1.SelectedValue = sdr("Type").ToString()
        'k4.Text = sdr("r4").ToString()
        con.Close()
    End Using
End Using

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jul 14, 2022 07:37 AM

Hi makumbi,

Use HasRows property of SqlDataReader class to check there is any record or not.

Dim strConnString As String = ConfigurationManager.ConnectionStrings("SMIS2022ConnectionString").ConnectionString
Using con As SqlConnection = New SqlConnection(strConnString)
    Using cmd As SqlCommand = New SqlCommand()
        cmd.CommandText = "SELECT * From Archivemax"
        ' cmd.Parameters.AddWithValue("@Id", ID)
        cmd.Connection = con
        con.Open()
        Dim sdr As SqlDataReader = cmd.ExecuteReader()
        If sdr.HasRows Then
            sdr.Read()
            Monthed.Text = sdr("Month").ToString()
            Expr2.Text = sdr("Expressed").ToString()
            types2term1.SelectedValue = sdr("Type").ToString()
            'k4.Text = sdr("r4").ToString()
        Else
            'Message to show does not have values.
        End If
        con.Close()
    End Using
End Using