This is a simple example of how to check for the existence of a username prior to letting someone select a username.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UserRegistration.aspx.cs" Inherits="UserRegistration" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>User Registration - Check Username Availability</title> </head> <body> <form id="form1" runat="server"> <asp:Label ID="lblUsername" runat="server"> Username: </asp:Label><br /> <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox> <asp:Label ID="lblUsernameError" runat="server" /> <p> <asp:Button ID="btnSubmit" runat="server" Text="Register" OnClick="btnSubmit_Click" /> </p> </form> </body> </html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration; // Only needed if you are pulling data from web.config.
public partial class UserRegistration : System.Web.UI.Page
{
// Load Connection String From Web.Config
public string SqlConnStr = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString();
// Windows Domain Account Access
//public string SqlConnStr = "Server=<Server Name/IP>;Database=<Database Name>;Integrated Security=True";
// SQL Server Account Access
//public string SqlConnStr = "Data Source=<Server Name/IP>;Database=<Database Name>;Persist Security Info=True;User ID=<Username>;Password=<Password>";
protected void Page_Load (object sender, EventArgs e)
{
}
public bool bUserExists (string sUsername)
{
bool bExists = false;
try
{
//Declare the connection object
SqlConnection Conn = new SqlConnection(SqlConnStr);
//Make the connection
Conn.Open();
//Declare the Command
using (SqlCommand cmd = new SqlCommand("select count(*) from [Usertable] where UserName = @UserName", Conn))
{
cmd.Parameters.AddWithValue("UserName", sUsername);
bExists = (int)cmd.ExecuteScalar() > 0;
}
if (bExists)
{
lblUsernameError.Text = "<br/><font style='color:red'>Username Exists, Please Try Another</font>";
}
else
{
lblUsernameError.Text = "<br/><font style='color:green'>Username Available</font>";
}
}
catch (Exception ex)
{
}
return bExists;
}
protected void btnSubmit_Click (object sender, EventArgs e)
{
bUserExists(txtUsername.Text);
}
}
Originally Posted on July 21, 2014
Last Updated on October 26, 2015
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.