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.

Recommended Answers

All 2 Replies

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.

Thanks alot. Yeah my logic was incorrect.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.