Checking for no records in a datareader

andycharger

Well-known member
Joined
Apr 2, 2003
Messages
152
I want to build a login page for my ASP.net solution.
Im doing this by connecting to the database, executing a SQL statement with the username in it.
What I want to do is find out if the user does not exist.
i.e. no records will come back.

How do I check for no records in a datareader?

Here is my code:

Code:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim strSql As String
        Dim strUsername As String
        Dim strPW As String

        Dim cnSQL As String

        cnSQL = "Server=localhost;DataBase=myDB; integrated Security=SSPI"


        strUsername = TextBox1.Text
        strPW = TextBox2.Text
        strSql = "Select * from Users where username = " & strUsername & ""

        CreateMySqlDataReader(strSql, cnSQL)

    End Sub
    Public Sub CreateMySqlDataReader(ByVal mySelectQuery As String, _
    ByVal myConnectionString As String)
        Dim myConnection As New SqlConnection(myConnectionString)
        Dim myCommand As New SqlCommand(mySelectQuery, myConnection)
        myCommand.Connection.Open()
        Dim strName As String
        Dim myReader As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
      
            While myReader.Read()
                strName = myReader("Username")
                If strName = "" Then
                    Response.Write("You must enter a valid logon name")
                Else
                    If TextBox2.Text = myReader("password") Then
                        must be a verified user
                        Response.Write("Logged on, " & strName)
                    Else
                        not verified
                        Response.Write("Password Invalid")

                    End If
                End If


                Console.WriteLine(myReader.GetString(0))
            End While
             myReader.Close()
        myConnection.Close()

    End Sub


Any help would be great.
 
Do the following :
If myReader.Read()
the reader returned a result thus valid user
else
no results so invalid user
End If

in your select query put the username and the password in the where clause.
Console.WriteLine(myReader.GetString(0))
 
reader.read would attempt to read the first record if it exists if it doesnot it returns False
 
How about this?

[VB]
Dim blnHasRecords As Boolean = False
While Read()
blnHasRecords = True
-The usual stuff here...
End While

If Not blnHasRecords
-No records found...
End If
[/VB]

By the way, Id advise you not to be too "friendly" (e.g., wrong username/wrong password) w/ your error msgs in the login screen. It would make your app easier to break into.
 
Back
Top