As a web developer we know that most of the time our application is having a login as well as the forget password kind of requirement.
Now, using visual studio 2005 it's very easy to design a login page because the inbuilt login tab has been added into the toolbox of VS 2005 editor, which has different types of control related to login functional.
Fig 1.1: New tab for login

Fig 1.2: All the controls of Login Tab
In the following article we will see that how to use login control using C#.Net. The following code will explain that how to authenticate the user against the database.
Step 1:- Drag and drop the login control on the page then the control will look like a login page at design time.

Fig 1.3: Login control at design time
Step 2: Once the UI is ready then will go ahead with the coding part to see how to write the code for this control.
To write the code for this code we need to handle the Login1_Authenticate event.
So, double click on the Login control it will generate the following code:-
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
bool Authenticated = false;
Authenticated = SiteLevelCustomAuthenticationMethod(Login1.UserName, Login1.Password);
e.Authenticated = Authenticated;
if (Authenticated == true)
{
Response.Redirect("Home.aspx");
}
}
private bool SiteLevelCustomAuthenticationMethod(string UserName, string Password)
{
bool boolReturnValue = false;
// Insert code that implements a site-specific custom
// authentication method here.
// This example implementation always returns false.
string strConnection = "server=dtpxp-skumari;database=master;uid=sa;pwd=;";
SqlConnection Connection = new SqlConnection(strConnection);
String strSQL = "Select * From Employee";
SqlCommand command =new SqlCommand(strSQL, Connection);
SqlDataReader Dr;
Connection.Open();
Dr=command.ExecuteReader();
while (Dr.Read())
{
if ((UserName == Dr["name"].ToString()) & (Password == Dr["Password"].ToString()))
{
boolReturnValue = true;
}
Dr.Close();
return boolReturnValue;
}
}
Login control is having a property called FailureText where you can write your own message.

Fig 1.4: Custom Error Message
Once you have passed the correct login credential then you will be redirected to the home page using the DestinationPageUrl property. DestinationPageUrl is the property of login control which is used to redirect the user to desination page after a successful login. If incorrect login credential it will show the message like "Your login attempt was not successful. Please try again". This is a custom message specified by the user through the FailureText property.
Fig 1.5: Logion Error
About inbuilt validation:- Login control is having a inbuilt validation feature which is available as a property for programmer. When you will drag-drop the control at design time you will see that the username and password textboxes are marked with star (*) sign which means these fields are required fields.
Fig 1.6: Validation
Login control is having some more features like specifying .CSS property, Button style etc.
Steps to use the sample:-
-
Download a zip file --> Unzip the file
-
Go to Start-->RUN-->inetmgr.exe
-
Go to Websites-->Default web sites
-
Right click on it-->NewVirtual Directory-->it will start the wizard
-
Map the unzip folder with the virtual directory-->finish
-
Run the application/Open the solution file.

Hoa NguyenPosted Jun 9, 2011, 10:02 AM
Thankx . I am a new web developer and our application requires to control the multiply login of each users . Means users could not login many times. Could you help me to add a login control multiply login from login.aspx.cs. Hoa
jitenderPosted Apr 10, 2011, 11:11 AM
http://msdn.microsoft.com/en-us/library/ms178329.aspx The Login control displays a user interface for user authentication. The Login control contains text boxes for the user name and password and a check box that allows users to indicate whether they want the server to store their identity using ASP.NET membership and automatically be authenticated the next time they visit the site. The Login control has properties for customized display, for customized messages, and for links to other pages where users can change their password or recover a forgotten password. The Login control can be used as a standalone control on a main or home page, or you can use it on a dedicated login page. If you use the Login control with ASP.NET membership, you do not need to write code to perform authentication. However, if you want to create your own authentication logic, you can handle the Login control's Authenticate event and add custom authentication code. http://msdn.microsoft.com/en-us/library/ms178329.aspx
mithun santhanamPosted Nov 3, 2010, 5:08 PM
Hi, I used the above code to create a login form.But I am getting an error saying: namespace Oledb connection could not be found ( are you missing a using directive or assembly reference). Could you please help me out...
LEx SaquitonPosted Oct 9, 2010, 4:28 AM
Please Email me a sample program of inventory using visual web developer and sql database [email protected] thank you.....
murali tsPosted Aug 29, 2010, 12:27 PM
Hi Susmita, Am learning C# and needs to create one project in my office,please tell h accme how to create backend database whic accepts the input from backend database to form and stores in backend with login credentials. It ll be more helpfull if u mail any material to [email protected] Eagerly waiting.
Matteo De LuciaPosted Aug 26, 2010, 12:36 PM
Hi. I'm a new c# developer and I've got a question for you. I created the login form and it works so well. I put it in my MasterPage. Now, I would hide the form when a user is logged and display a message of welcome. I tried by using visual studio's <LoginView> and <AnonymousTemplate> but it doesn't work. Can you help me? Thank you so much
Shahid AfzalPosted Jul 2, 2010, 6:45 AM
I am new in .net development and start development from 3.5.Today I tried this demo.Its work properly.I am using 3-tier architechure.Can you help me for designing master page for data-driven web application.
B M SuchitraeditedPosted Jun 22, 2010, 8:40 AMEdited Jan 16, 2013, 4:45 AM
Hello mam ur articles and source codes helped a lot.. can u plzz help me filter multiple dropdownlist controls.. how to do it plzz post codes
islam faragPosted Jun 7, 2010, 5:08 AM
i have an error called "Not all code paths returns a value" could you help me to fix it
islam faragPosted Jun 7, 2010, 5:01 AM
i have incorporate the code into my project but there's an error called"Error 44 '_Default.SiteLevelCustomAuthenticationMethod(string, string)': not all code paths return a value D:\Documents and Settings\Eslam\My Documents\Visual Studio 2008\WebSites\project\Default.aspx.cs 38 18 D:\...\project\ " could you help me fix it Thanks.
amol girasePosted May 13, 2010, 1:01 PM
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace first { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { int Ctr; string LoginName, Passoerd; LoginName = txtUserName.Text; Password = txtPassword.Text; Ctr = Ctr + 1; if ((LoginName == "sa") && (Password == "callcenter")) { lblMessage.Visible = true; lblMessage.Text = "Welcome to Diaz Telecommunication"; Ctr = 0; } else if (Ctr < 3) { lblMessage.Visible = true; lblMessage.Text = "Incorrect User Name or Password. Please try again."; txtUserName.Focus(); } else { MessageBox.Show("Unauthorized Access. Aborting..."); Close(); } } } } Error 1 The name 'Password' does not exist in the current context 42 13 first Error 2 The name 'Password' does not exist in the current context 44 41 first
Samuel EdwardsPosted Apr 1, 2009, 10:14 AM
Hi, I'm using VB as my language. Can I use the format you have to login?
Benny MathewPosted Dec 23, 2008, 12:07 PM
hi Used this code,but i got this error: is inaccessible due to its protection level can anybody help! ben
reshma hankarePosted Dec 15, 2008, 1:27 AM
actually i have run your code,but its giving me error,indexOutOfRangeException was handled by usercode.inside the while loop,username and password is it the name of column of login table.pls help me
sanjeev ranjanPosted Dec 4, 2008, 12:46 AM
hey sush i have got it thanks....
sanjeev ranjanPosted Dec 4, 2008, 12:39 AM
Hi sushmita i have tried yor code but i am able to use only 1st row of data from database... i m not able to login using data from second row onwards.. can u help me ???
Vikram RathorePosted Nov 18, 2008, 1:59 AM
I read your How to use Login Control in Visual Studio 2005. thank you very much. but your article has bad download file. there are tow WebSite3.sln, WebSite3.suo files. no aspx, cs files. please check the other files. and I must say Thank you. ^^. Vikram Singh Rathore, Mentor, Centre For Electronic Governance, Govt of Raj. Jaipur
AnonymousPosted Nov 7, 2008, 2:15 AM
hi your post was really helpful. however, in case of successful login, if i want the login system to point to another visual studio application, how do i do that? thanks
AnonymousPosted Nov 2, 2008, 8:16 PM
Hi, what if in case of a successful login, instead of pointing to an url, i want it to point to another visual studio application. How do i do that? Thanks, Abhinav
GreenPosted Sep 15, 2008, 10:43 AM
Short, simple and sweet. This article is gets the job done well.
GreenPosted Sep 15, 2008, 10:43 AM
Short, simple and sweet. This article is gets the job done well.
yamunaraniPosted Mar 14, 2008, 3:56 AM
i want sample for all login controls
Uma RamiyaeditedPosted Feb 20, 2008, 4:34 AMEdited Feb 20, 2008, 4:36 AM
Can you please tell me the role of Remember me checkbox. And how to use it
tariq hussainPosted Feb 7, 2008, 3:03 PM
plz send me complete code of article of login control published in c-sharpcorner.com thanks, [email protected]
sey sandersPosted Feb 1, 2008, 8:16 PM
Great articale and learning aid for a newbie like me . If someone can post the final bug free version that will be alsome.
RAVIKUMAR PRABHAKARPosted Jan 17, 2008, 12:58 AM
What is the use of Remember me checkbox and then please help me how to use it.
Katrin WilhelmPosted Jan 12, 2008, 11:55 PM
Hi Sushmita, Thanks for the code - it works fine except that when I log on and get redirected the system does not keep the user logged in hence I get redirected to the logon page. Is there anything else I need to do so that a session variable is written? And if I download the source files they are empty... Thanks for you help. Kat
Raghu NandanPosted Jan 10, 2008, 6:35 AM
am working with win app and i want to print textbox info how can i achive that
Palaneeswar ChittoorPosted Dec 5, 2007, 8:52 AM
hey that was a gr8 code which made my first strides into logincontrol made a bit easy... but i changed the code a bit... u forgot to close the sqlconnection after opening it..so,i did that in my appication..and sending it..users please change some of the variables as i used them according to my use..thanks sushmitha kumari public bool SiteLevelCustomAuthenticationMethod(string usr, string pwd) { bool boolReturnValue = false; string User = usr; string Passwd = pwd; SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Pubs"].ConnectionString); String strSQL = "Select * From LoginUsers"; SqlCommand command = new SqlCommand(strSQL, Connection); SqlDataReader Dr; try { Connection.Open(); Dr = command.ExecuteReader(); while (Dr.Read()) { if ((User == Dr["Username"].ToString()) & (Passwd == Dr["Password"].ToString())) { boolReturnValue = true; break; } } Dr.Close(); } catch (Exception ex) { Login1.FailureText = ex.Message.ToString(); Response.Redirect("LoginForm.aspx"); } finally { Connection.Close(); } return boolReturnValue; }
Naresh KrishnaPosted Dec 4, 2007, 1:59 AM
i had read ur artical but how can i dodo wnload tghe artical how can i download source code
Naresh KrishnaPosted Dec 4, 2007, 1:59 AM
i had read ur artical but how can i download tghe artical
ruchi goyalPosted Nov 21, 2007, 3:31 AM
hi, itz a gud article. but i cant acces the files in website2.zip after downloading. there are no files in the folder. plz help..
David FullerPosted Nov 14, 2007, 6:14 AM
My application now logs in.. great.. .... if you are the first person in the database table! the datareader doesn't look through all the rows to find the correct user details. could someone please, please help with this asap Thanks David
mukesh mrPosted Sep 6, 2007, 2:58 AM
hi, i have gone through this. but i got an error while trying the codes. its like this.."Error 1 '_Default.SiteLevelCustomAuthenticationMethod(string, string)': not all code paths return a value"
sathish kumarPosted Aug 27, 2007, 7:20 AM
i use login control code.. but here is error... help me how to use login controls in asp.net. give step by step procedure... please
arshadPosted Jul 12, 2007, 5:38 AM
i was worried how can i use this control ur article looks can u please send the final code after correction to my email arsmcasa@yahoo and i need the code for sending email in c#.net plz thanks you Arshad
murugenthiran karthikeyanPosted Jun 30, 2007, 5:35 AM
Hi,It can be easily understandable for those who are new to .net2.0
murugenthiran karthikeyanPosted Jun 30, 2007, 5:35 AM
Hi,It can be easily understandable for those who are new to .net2.0
DVR PrasadPosted Jun 15, 2007, 2:50 AM
Hi Sushmita, We are using ASP.NET Login Control. I want to fire a javascript function on click of button in the Login Control. I am unable to attach OnClick Event to that button which is available in Login Control. If u can please help me it will greateful. Thanks DVR Prasad
rejaneeshPosted Jun 11, 2007, 6:13 AM
This is something realy very nice 2 understand... U had done a great job.. Congrates...
Piyush KoratPosted May 18, 2007, 3:30 AM
Hi its very nice article. I want to disable Cut/Copy/Paste into Password field whereas keep enable it into Username field How could i achieve this?
dost indPosted May 7, 2007, 2:00 PM
Thanks darling
nandhaPosted Apr 25, 2007, 2:15 AM
i could not open the source code thanks
Xiaoyan LiuPosted Apr 20, 2007, 12:44 PM
I try to add a query string in the redirect. it works at my local machine, but it did not work after I publish it into our web server. Thanks, June
Sridhar PettelaPosted Apr 14, 2007, 8:01 AM
this is the error - Login.SiteLevelCustomAuthenticationMethod(string , string)':not all code paths return a value
Sridhar PettelaPosted Apr 14, 2007, 8:00 AM
this is the error - Login.SiteLevelCustomAuthenticationMethod(string , string)':not all code paths return a value
aspeditedPosted Apr 11, 2007, 4:36 AMEdited Apr 11, 2007, 4:41 AM
Error
aspeditedPosted Apr 11, 2007, 4:12 AMEdited Apr 11, 2007, 4:39 AM
hi there is error when i run the code while (Dr.Read()) Invalid attempt to Read when reader is closed. please help
Chetan RanpariyaPosted Apr 9, 2007, 6:58 AM
Hi Sushmita, This is very good article. I am was very confused regarding how to user login control. This article helped me a lot to start with. Thanks and regards, Chetan Ranpariya.
HawkmothPosted Mar 20, 2007, 12:08 PM
I am using the Login contol and everything is working great when I use it localy. When I access the same sight from another pc the login control seems to accept my login but I am unable to get to a authenticated members only page and the loginstatus control suggests I'm not loged in. I guess i have a problem with the way my site is set up or the web.config file is maybe wrong. can anyone help?
Ashwani DwivediPosted Mar 1, 2007, 9:27 AM
How to use properly if we simply drag and drop login control it will not work for that we have to use Asp.net configuration so how do use that process please give the detail my id is [email protected]
mmmPosted Feb 26, 2007, 5:48 AM
and the code not working
rajeshPosted Feb 12, 2007, 2:34 AM
if we set roles an users in the asp.net cofiguration,it creates its own data base an store the user an roles.how to add ourown data base an acess the role an user(in login control)
david eliePosted Nov 16, 2006, 4:37 PM
very nice. thank you very much. though you have a small error. if i run the code the way it is written, i get an error: "Not All Code Paths Return A Value" message that is simply because your : return boolReturnValue; statement is inside the while loop and therefore not all possible values are returned. simply take this piece of code and place it outside the while loop. p.s : i am sure that it was a typing error. thanks again.
venkat chalkPosted Oct 27, 2006, 3:10 AM
Hi susmita kumari, ur article is good, iam trying to run this application but it is giving error like.. "Not all code paths return a value" error is rising T,,, SiteLevelCustomAuthenticatedMethod(string UserName,string Password) so plz help me.. thanks...
PettrerPosted Oct 23, 2006, 3:23 AM
Hi, Thank you very much for your neat article on using the login control! I made a VB version of it, here it is (in case someone sees this post and needs it in VB): http://forums.asp.net/thread/1431652.aspx I'm trying to create more of the login controls programatically, as you have been doing (it's the only way - except for rewriting the membership providers that is - to skip the cluttered default db solution provided by Visual Web Developer and to use the login stuff to one's own, existing, db). However, I've run into problems creating the CreateUserWizard (I haven't tried the other controls yet). Do you by any chance have some code for this (or the other controls)? I think posting code for these controls would benefit a LOT of coders, by judging of the vast amount of questions on this subject on forums.asp.net. In any case, thanks again for your code + tutorial! Pettrer, Sweden
Srinivas AkulaPosted Aug 13, 2006, 12:27 PM
Hi I don't need the Remember Me option. How to disable 'Remember Me Check box'? Thanks
Sushmita KumarieditedPosted Jun 21, 2006, 2:38 AMEdited Nov 2, 2006, 11:43 PM
Long back i have uploaded this file.Now i don't know where is the actual copy in my machine.U just follow the steps and the programe will work if not you ask me i will help u. Sushmita
Douglas VegaeditedPosted May 24, 2006, 4:54 PMEdited May 24, 2006, 4:55 PM
I tried to open your example to see the Web.Config because my application don't deny user access to the pages, but the ZIP don't have the files of the project. Can you display the Web.Config? tanks
chunsang leePosted Feb 16, 2006, 4:49 AM
I read your How to use Login Control in Visual Studio 2005. thank you very much. but your article has bad download file. there are tow WebSite3.sln, WebSite3.suo files. no aspx, cs files. please check the other files. and I must say Thank you. ^^. - chun sang -