0

Hi,

I am trying to check if the username entered by the user in the textbox exists in the Access database I am using. For some reason, I am unable to get this correct.

My code is as follows:

Protected Sub btnRegister_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRegister.Click

        Dim sql As String = "select * from Registration where Username='" & TxtUsername.Text & "'"

        Dim con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=H:\ASP\App_Data\Register.mdb")
        Dim cmd As New OleDbCommand(sql, con)

         con.Open()
        Dim reader As OleDbDataReader = cmd.ExecuteReader()

        If Not reader.Read Then
            ' Login was unsuccessful
            ' Show error message in a label
            lblDisplay.Text = "username is already taken, please choose another username"

            reader.Close()
            con.Close()

        Else

            adsRegistration.InsertParameters("Username").DefaultValue = TxtUsername.Text
            adsRegistration.InsertParameters("Password").DefaultValue = txtLPassword.Text
            adsRegistration.InsertParameters("Email").DefaultValue = txtEmail.Text
            adsRegistration.Insert()

            lblDisplay.Text = "Congratulations! Your account has been created." 
        End If


    End Sub

When I execute this code, it does not execute the IF part. It executes the Else statement and gives an error stating that duplicate value of a primary key cannot be created.

2
Contributors
2
Replies
4
Views
5 Years
Discussion Span
Last Post by babydol
0

It seems to me you have your logic round the wrong way. If the data reader can't read then there are no rows so the user name isn't entered. If the reader has rows then the name is taken and you inform the user of that.
You need to swap your code around in the if...else statements.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.