ASP.NET - how make sure that there is no duplicate value for username.

Asked By aman on 02-Nov-11 07:04 AM
hi all,

i want to create a page for user registration and my requirement is that their should be not duplication for the user name
to stored in the database.

please help me with some example


thanks
dipa ahuja replied to aman on 02-Nov-11 07:07 AM
Untitled document
Markup
 
<asp:UpdatePanel runat="server" ID="up1">
   <ContentTemplate>
     Username:
     <asp:TextBox runat="server" ID="Username" AutoPostBack="true" OnTextChanged="Username_Changed" />
     <div runat="server" id="UserAvailability">
     </div>
     <br />
   </ContentTemplate>
</asp:UpdatePanel>
 
Code Behind:
 
protected void Username_Changed(object sender, EventArgs e)
{
   if (!checkExist(Username.Text))
   {
     UserAvailability.InnerText = "Username taken, sorry.";     
  }
   else
   {
     UserAvailability.InnerText = "Username available!";
   }
}
 
public bool checkExist(string s)
{
   string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
  
  SqlDataAdapter da = new SqlDataAdapter("Select name from people where name='"
     + s + "'", conn);
 
   DataTable dt = new DataTable();
   da.Fill(dt);
 
   if (dt.Rows.Count > 0)
   {
     return false;
   }
   else
   {
     return true;
   }
}
Jitendra Faye replied to aman on 02-Nov-11 07:07 AM
Use this code-


protected void btnSubmit_Click(object sender, EventArgs e)

{

if (TxtUserName.Text != "" && TxtPassword.Text != "")

{

SqlConnection con = new SqlConnection("con string");

SqlDataAdapter da;

string mySQL = "SELECT * FROM logintable where username='" + TxtUserName.Text + "' and password='" + TxtPassword.Text + "'";

da = new SqlDataAdapter(mySQL, con);

con.Open();

DataSet ds = new DataSet();

da.Fill(ds);

if (ds.Tables[0].Rows.Count > 0)

{

Response.Write("<script>alert('Already Exist')</script>");

}

else

{

//Write Insert code

}

}

USE THIS CODE AND LET ME KNOW.

Kirtan Patel replied to aman on 02-Nov-11 02:45 PM
you can put Contrain on database column to be unique and notnull ! now if user enteres username already take n then code will fire exception if he tries to register handle that exception properly in code and provide user appropriate feed back
 
private void button1_Click(object sender, EventArgs e)
{
  /* Insert Data into Database */
  SqlConnection con = new SqlConnection("Connection String");
  con.Open();
  SqlCommand comm = new SqlCommand("insert into tableA values(@val1,@val2,@val3)", con);
  comm.Parameters.Add("@val1", TextBox1.Text);
  comm.Parameters.Add("@val2", TextBox2.Text);
  comm.Parameters.Add("@val3", TextBox3.Text);
  try
  {
    comm.ExecuteNonQuery();
  }
  catch(SqlException ex)
  {
    /* Handle the Exception ex and Provide Feed back to user about Error" */
  }
 
  /* Close the Connection*/
  con.Clo