Preventing duplicate User Names with ASP.NET
I have a registration form.I want to prevent duplicate User Names with ASP.NET.Now,I can do to prevent duplicate User Names.But,I want to give a warning message to User.How can I do that?
Code:
try{
SqlCommand cmd = sqlConnection.command("If not exists (Select user_name from users Where user_name=@userName) Insert into users(userId,user_name,user_su开发者_JAVA百科rname,email) Values (@userID,@userName,@userSurname,@email)");
SqlParameter p1 = new SqlParameter("@userID", Session["userID"].ToString());
SqlParameter p2 = new SqlParameter("@userName", txt_userName.Text);
SqlParameter p3 = new SqlParameter("@userSurname", txt_surName.Text);
SqlParameter p4 = new SqlParameter("@email", txt_email.Text);
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
cmd.Parameters.Add(p4);
cmd.ExecuteNonQuery();
myConnect.close();
}
catch (Exception ex)
{
Response.Write("<script>alert("+ex.Message+ ")</script>");
}
}
ExecuteNonQuery
returns number of rows affected by command. In your case it will be either 0(not inserted) or 1(inserted).
int res = cmd.ExecuteNonQuery();
if (1 != res)
{
//show warning
}
Seems like your storing user accounts in a database on you own. Why don't you use the ASP.NET Membership
framework? you can configure various settings in the membership framework including Unique Email Addresses
. I don't remember exactly right now whether it supports unique usernames too or not, but it'd be a better idea to use the framework overall.
ASP.NET 2.0 Membership Framework
精彩评论