Hassan
Hassan

Reputation: 45

how to check existed username when signUp

I want to check if the username is already exist or not. this what I've reached but it's not working.

 Dim cmdstr As String = "Select count(*) from Registration where username = '" & txtName.Text & "'"
 Dim userExist As SqlCommand = New SqlCommand(cmdstr, con)
 Dim temp As Integer = Convert.ToInt32(userExist.ExecuteScalar().ToString())
    If (temp = 1) Then
       Response.Write("user name is already Exist!!")
    End If

Upvotes: 1

Views: 108

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460068

  1. Your open for SQL-Injection. Don't concatenate strings to a sql-query but use SqlParameters
  2. You haven't opened the connection (i assume)

Here's a full sample:

Public Shared Function GetUserCount(userName As String) As Int32
    Const sql = "SELECT COUNT(*) FROM Registration where username = @UserName"
    Using con As New SqlConnection(connectionString)
        Using cmd = New SqlCommand(sql, con)
            cmd.Parameters.AddWithValue("@UserName", userName)
            con.Open()
            Using reader = cmd.ExecuteReader()
                If reader.HasRows
                    reader.Read()
                    Dim count As Int32 = reader.GetInt32(0)
                    Return count
                End If
            End Using
        End Using
    End Using
End Function

and use the method in this way:

Dim userCount As Int32 = GetUserCount(txtName.Text.Trim())
If userCount > 0
    LblWarning.Text = "User-name already exists!"
End If 

Upvotes: 1

Related Questions