title: Check if username exist in asp.net using stored procedure and adding values to Registration.aspx
body: <p>I've created a stored procedure in SQL Server to check if username exists in the database:</p>
  
  <pre><code>CREATE PROCEDURE [dbo].[spCheckUsernameForAnswer]
       @username VARCHAR(30)
  AS
  BEGIN
      DECLARE @count INT
  
      SELECT @count = COUNT(username) 
      FROM Users 
      WHERE [username] = @username 
  
      IF (@count = 1)
      BEGIN
          SELECT 1 AS ReturnCode
      END
      ELSE
      BEGIN
          SELECT 0 AS Returncode
      END
  END
  </code></pre>
  
  <p>Here is what I've done in Visual Studio <code>Registration.aspx.cs</code>. </p>
  
  <p>I need to check if the username exists and if not to insert the required values into db to register a new user.</p>
  
  <p>From the code below it keeps registering new users with the same username again and again. </p>
  
  <p>Any idea what am I missing here?</p>
  
  <pre><code>protected void Button1_Click(object sender, EventArgs e)
  {
      try
      {
          Guid newGUID = Guid.NewGuid();
  
          SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
  
          SqlCommand cmd = new SqlCommand("spCheckUsernameForAnswer", conn);
          cmd.CommandType = CommandType.StoredProcedure;
  
          SqlParameter parausername = new SqlParameter("@username", TextBoxUN.Text);
          cmd.Parameters.Add(parausername);
  
          conn.Open();
  
          SqlDataReader rdr = cmd.ExecuteReader();
  
          while (rdr.Read())
          {
              if (Convert.ToBoolean(rdr["ReturnCode"]))
              {
                  Label1.Text = "Username found";
              }
              else
              {
                  Label1.Text = "not found";
              }
          }
  
          conn.Close();
  
          SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
  
          conn1.Open();
  
          string insertQuery = "insert into [Users] (user_id, first_name, last_name, email, username, password) values (@user_id, @first_name, @last_name, @email, @username, @password)";
  
          SqlCommand com = new SqlCommand(insertQuery, conn1);
  
          com.Parameters.AddWithValue("@user_id", newGUID.ToString());
          com.Parameters.AddWithValue("@first_name", TextBoxFname.Text);
          com.Parameters.AddWithValue("@last_name", TextBoxLname.Text);
          com.Parameters.AddWithValue("@email", TextBoxEmail.Text);
          com.Parameters.AddWithValue("@username", TextBoxUN.Text);
          com.Parameters.AddWithValue("@password", TextBoxPass.Text);
  
          com.ExecuteNonQuery();
  
          Response.Write("Registration successful");
  
          conn1.Close();
      }
  }
  catch (Exception ex)
  {
      Response.Write("Error:" + ex.ToString());
  }
  </code></pre>