Thursday, November 27, 2008

How to make 'userid' Unique?

Hello Friends!

Today I want to share with you most common functionality while you develop any registration page.
You dont want to make userid as primary key but you still want to make it unique.How?
That is Simple.You need to first access all the data in Register table in to a DataSet (say Ds).

Let us consider txtUserName as ID of TextBox in which user enters his 'userid'.

The keypoint here is the user who is registering may be the first user of you.Then Your database contains nothing.You also need to check this condition.

A Label with ID as 'lblCheck' displays the availability of userid.

The Code part will be as shown below :

if (ds.Tables["user"].Rows.Count > 0)
{
string uname = txtUserName.Text;

foreach (DataRow R in ds.Tables["user"].Rows)
{
if (uname.CompareTo(R["userid"].ToString()) == 0)
{
lblCheck.Visible = true;
lblCheck.Text = "Unavailable ,Please Choose another name.";
break;
}
else
{
lblCheck.Visible = true;
lblCheck.Text = "Username available.";
}
}
}
else
{
lblCheck.Visible = true;
lblCheck.Text = "Username available.";
}


Aliter :


There is another way to do this.Using command object and SqlDataReader we can simply write code as
below:

cmd = new SqlCommand("select * from Register where userid='"+txtUserName.Text+"'",con);
con.Open();
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
lblCheck.Visible = true;
lblCheck.Text = "Unavailable ,Please Choose another name.";
}
else
{
lblCheck.Visible = true;
lblCheck.Text = "Username available.";

}

No comments: