Lorenzo Salamante
Lorenzo Salamante

Reputation: 37

Determining if a query returns 'no rows' in vb.net

I am using MS SQL Server as my database and VB.NET as my back-end.

I want to determine if my query in sql command text returns no rows. I tried to have a query that returns no rows, and then give its value to a text box which became 0. (integer)

The problem now, is that when I test it in an If condition, it doesn't work. The code is like this:

If (Query that returns no rows) = 0 Then
'condition
Else
'condition
End If

I tried a blank string, but it still does not work. Please help! If possible, please give the simples solution to the problem. Thank you in advance!

Upvotes: 0

Views: 10894

Answers (2)

mabees
mabees

Reputation: 63

        Dim RowsReturned As Integer
        Cmd.CommandText = "SELECT * FROM tblExample WHERE PKeyNo =999"
        cmd.CommandType = CommandType.Text


        RowsReturned = cmd.ExecuteScalar()

        If RowsReturned = 0 Then
                'No rows
        Else 
           'Has Rows

Upvotes: 0

Deepshikha
Deepshikha

Reputation: 10284

@podiluska is right. You will have to execute the command. As I can see you have assigned value for the CommandText property of Command object that’s the query you want to execute. In order to execute the command, you must have an open active connection followed by call to Execute method on command object. Following pseudo code might help:

Public Sub Temp(ByVal connectionString As String)
    Dim queryString As String = _
       " select * from example where id = 999;" 
    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand(queryString, connection)
        connection.Open()
        Dim reader As SqlDataReader = command.ExecuteReader()
        Try 
            If reader.Read() Then
               'If condition
            Else
               'condition with  no results
            End If
        Finally 
            reader.Close()
        End Try 
     End Using 
End Sub

Upvotes: 1

Related Questions