How to check username availability and uniqueness in ASP.NET?
In the simplest way: how can I check username availability?
When I enter a new user in a textbox and click on check availability button, if it is available it s开发者_如何转开发hould display in green color that the username is available. And there should not duplicate usernames. I mean two username should not be identical.
If you're using the ASP.NET membership, you can just do:
string userNameToCheck = txt_Username.Text;
MembershipUser existingUser = Membership.GetUser(userNameToCheck);
bool exists = existingUser != null;
If you're using a database structure different to ASP.NET membership, you just have to do a like
query on your user table (replacing UserTable, UserName and 'Username' respectively):
SELECT *
FROM
UserTable
WHERE
UserName Like 'Username'
If you retrieve any results back, then that username has already been used.
Assuming you are storing the usernames in the database, you can make an Ajax call to check the availability in the database. jQuery has an excellent Ajax library.
suppose you have username and password fields in your application.. when you enter something in username and click on tab,we have to check whether the username available or not... now i explain here
In the above page i have 2 boxes... double clcik on username textbox.. it will go to
protected void txtUsername_TextChanged(object sender, EventArgs e) { }
[txtUsername is the name of my username textbox]
now in that txtUsername_Textchanged event we have to write the code for availability of user..
whatever we are giving in username,it will compare with username column in database.. so first we retrieve the username column values in data reader.. then if we have rows in data reader then that username has already taken,if not it is available..
protected void txtUsername_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtUsername.Text))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ymk"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select Location from Data where Location=@Name", con);
cmd.Parameters.AddWithValue("@Name", txtUsername.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
lblStatus.Text = "UserName Already Taken";
}
else
{
checkusername.Visible = true;
lblStatus.Text = "UserName Available";
}
}
else
{
checkusername.Visible = false;
}
}
精彩评论