For my sign up page, i want detect user exist so that no repeated username. BUT fail. There is no error in my coding. BUT cannot detect....

HELP. tHAnk you

if (IsPostBack)
            {
                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString);
                con.Open();
                string cmdStr = "Select count(*) from Reg where Username = '" + txtUsername.Text + "'";

                SqlCommand userExist = new SqlCommand(cmdStr, con);
                int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());

                con.Close();

                if (temp == 1)
                {
                    Label5.Visible=true;

                }

            }

Dani AI

Generated

Quick summary and what to check (ties together the helpful points from , and ):

  • is right to ask for a debug of the returned value — print or log the value your query returns to see what’s actually coming back.
  • is correct that testing == 1 is fragile; the test should treat any count > 0 as “exists.”
  • is right to call out SQL injection and the need for parameterized queries and proper disposal of connections.

Most likely causes seen in this thread: the code is querying the wrong control/column (Email vs Username), the logic only checks == 1 instead of > 0, or the connection string/table being queried is not the one expected.

Safe, reliable server-side pattern (do the existence check right before the insert; use parameters and using-blocks):

string connStr = ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString;

using (var conn = new SqlConnection(connStr))
using (var cmd = new SqlCommand("SELECT COUNT(1) FROM Reg WHERE Username = @u", conn))
{
    cmd.Parameters.Add(new SqlParameter("@u", SqlDbType.NVarChar, 100) { Value = txtUsername.Text.Trim() });
    conn.Open();
    bool usernameExists = (int)cmd.ExecuteScalar() > 0;
    Label5.Visible = usernameExists;
    if (usernameExists) return; // stop, show message
}
// proceed with parameterized INSERT (do not use string concatenation)

Additional best practices and troubleshooting checklist:

  • Add a UNIQUE constraint/index on Username so the DB enforces uniqueness (e.g. ALTER TABLE Reg ADD CONSTRAINT UX_Reg_Username UNIQUE (Username)); handle the duplicate-key SqlException as a last-resort protection against race conditions.
  • Trim input and be conscious of collation/case-sensitivity. Test the same SELECT in SSMS with the exact value from the textbox to rule out data/typo problems.
  • Use server-side validation (CustomValidator or check in btnSignUp_Click) and optionally an AJAX/textbox TextChanged (AutoPostBack) routine for immediate feedback.
  • Never store plaintext passwords — use a modern, salted hash (PBKDF2/BCrypt/Argon2).

If the check still fails after these changes, log the final SQL/parameter values and verify the connection string to ensure the code is talking to the expected database.

Recommended Answers

All 4 Replies

First off, debug your code and see what value is being put into temp. If the user name was in your database twice then temp would be more than 1, if it isn't there at all then temp won't be 1 either.

commented: tq... +0
 Hi hericles, i can't get what you mean... Below is my full coding... thanks

 protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString);
            con.Open();
            string cmdStr = "Select count(*) from Reg where EmailAddress = '" + txtEmail.Text + "'";

            SqlCommand userExist = new SqlCommand(cmdStr, con);
            int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());

            con.Close();

            if (temp == 1)
            {
                Label5.Visible=true;

            }

        }
    }
    protected void btnSignUp_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString);
        con.Open();
        string insCmd = "Insert into Reg (Username, FullName, EmailAddress, PhoneNumber, Password, State) values (@Username, @FullName, @EmailAddress, @PhoneNumber, @Password, @State)";
        SqlCommand insertUser = new SqlCommand(insCmd, con);
        insertUser.Parameters.AddWithValue("@Username", txtUsername.Text);
        insertUser.Parameters.AddWithValue("@FullName", txtFullname.Text);
        insertUser.Parameters.AddWithValue("@EmailAddress", txtEmail.Text);
        insertUser.Parameters.AddWithValue("@PhoneNumber", txtPhone.Text);
        insertUser.Parameters.AddWithValue("@Password", txtPassword.Text);
        insertUser.Parameters.AddWithValue("@State", DropDownListState.SelectedItem.ToString());


        try
        {
            insertUser.ExecuteNonQuery();
            con.Close();
            Response.Write("<script>alert('Sign Up Successfully')</script>");
            Response.Redirect("Login.aspx");

        }

        catch (Exception)
        {
            Label6.Visible = true;

        }

        finally
        {

        }
    }

What hericles means is that just simply check to see what is being stored in temp. do a response.write or assign the value to a control.

The reason is that according to your code the if..then will only be true if temp equals 1. What about if you had two accounts, then it would be false, but that would not be desireable because you would create a third account. This is a logic problem, not a coding syntax issue.

commented: tq... +0

What will happen when a user type following in the TextBox:

hello' or '1'='1

One must have to avoid the SQL Injection by creating stored procedure or parameterized query.

string cnstr=ConfigurationManager.ConnectionStrings["RegConnectionString"]
                                        .ConnectionString;
bool found=false;
using(SqlConnection con = new SqlConnection(cnstr))
 {
   string cmdStr = "Select username from Reg where Username = @username";
  using(SqlCommand userExist = new SqlCommand(cmdStr, con))
   {
     con.Open();
     object result=userExist.ExecuteScalar();
     if(result!=null)
       found=true;
    }
 }
 if(found)
    //
else
    //
commented: tq... +0
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.