Introducing DotNetFunda.com on mobile http://m.dotnetfunda.com ! Be with DotNetFunda.com on the go !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 5039 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > How to Write a Simple login page in Asp.net

How to Write a Simple login page in Asp.net

5 vote(s)
Rating: 4.8 out of 5
Article posted by Vuyiswamb on 3/5/2010 | Views: 128290 | Category: ASP.NET | Level: Beginner red flag


Yesterday I stumbled across a post that was posted on our forum. I was very busy with other things, when Sheo started a conversation based on that post. I was looking at it until he updated the untagged code that was posted. By looking at the Stored Procedure I could see that the poster was lost and his Stored Procedure approach failed him. In this Article am going to explain how to write a simple login in Asp.net.

Using the code

We are going to user C# as our language.

Start

Open Visual Studio and Create a New Website. Automatically you will have an empty page defined for you like this

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 id="Head1" runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

</div>

</form>

</body>

</html> 

Go to Design View and you will notice there is nothing on your page. Now open your Toolbox and add a buttons and some textbox and depicted in the following.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 id="Head1" runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Label ID="lblUsername" runat="server" Text="Username"></asp:Label>

&nbsp;&nbsp;&nbsp;&nbsp;

<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>

<br />

<br />

<asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>

&nbsp;&nbsp;&nbsp;&nbsp;

<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>

<br />

<br />

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<asp:Button ID="btnlogin" runat="server" Text="Login" onclick="btnlogin_Click"

Width="47px" />

&nbsp;

<asp:Button ID="btnCancel" runat="server" Text="Cancel"

onclick="btnCancel_Click" />

<br />

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>

</div>

</form>

</body>

</html>

And your Design should look like this

Now as you can see our login page is created, Let us see how we can validate the login and what is needed to have a proper login. Open your Sql management Studio and Create a New Database, but if you already have it you will just follow the Step 2 where we add a table.

Step 1: Create a Database

Create Database FORUM


Step 2: Create a Table

CREATE TABLE [dbo].[Log_Users]
(
 [Logid] [int] IDENTITY(100,1)PRIMARY KEY NOT NULL,
 [Username] [varchar](55) NOT NULL,
 [PASSWORD][varchar](55),
 [Time_Logged_in] [datetime] NOT NULL,
 [Time_Logged_Out] [datetime] NOT NULL,
 [Status] [int] NOT NULL,
 [Date_Logged_in] [datetime] NOT NULL,
 [E_MAIL] [varchar](55) NOT NULL
 )


Step 3: Let us Add Sample Data

insert into dbo.Log_Users
values('Vuyiswamb','wowididit',GETDATE(),'02/07/2010',1,GETDATE(),'Vuyiswa@wow.com')

insert into dbo.Log_Users
values('SheoNarayan','Oops?',GETDATE(),'02/09/2010',1,GETDATE(),'Sheo@wowMail.com')

Now that we have our sample Data. Please note that you can use any other field but the username and Password fields are the most important. Now let us create our stored Procedure.

Step 4: Create a Stored Prcedure that will validate and return a valid Integer.

Create Proc [dbo].[prcLoginv]
 (
 @Username VarChar(50),
 @UPassword varChar(50),
 @OutRes int OUTPUT
 )
 AS
set @OutRes = (SELECT count(*) FROM [dbo].Log_Users
WHERE Username = @Username And [Password] = @UPassword)
if(@OutRes = 1)


begin

set @OutRes 1--Login is Correct
end

else

begin

set @OutRes = 0  --Bad login
end

In the above Stored Procedure we count the Records that have matched the Records and if there is one record found then it is a good login else it is a bad login. But how will you use this in your asp.net Page. First we have to create a Function that will access the stored procedure and call that function in click event of the button. Create a Function as show below in your page not inside your page load because you will get an Error.

public int Validate_Login(String Username, String Password)

{

SqlConnection con = new SqlConnection(@"User id=sa;Password=Dotnetfunda;Server=VUYISWA\VUYISWA;Database=Forum");

SqlCommand cmdselect = new SqlCommand();

cmdselect.CommandType = CommandType.StoredProcedure;

cmdselect.CommandText = "[dbo].[prcLoginv]";

cmdselect.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = Username;

cmdselect.Parameters.Add("@UPassword", SqlDbType.VarChar, 50).Value = Password;

cmdselect.Parameters.Add("@OutRes", SqlDbType.Int, 4);

cmdselect.Parameters["@OutRes"].Direction = ParameterDirection.Output;

cmdselect.Connection = con;

int Results = 0;

try

{

con.Open();

cmdselect.ExecuteNonQuery();

Results = (int)cmdselect.Parameters["@OutRes"].Value;

}

catch (SqlException ex)

{

lblMessage.Text = ex.Message;

}

finally

{

cmdselect.Dispose();

if (con != null)

{

con.Close();

}

}

return Results;

}

As you can see this Function return an Integer, as we said before this will return either a 1 which is equal to “Good” and other numbers will be “Bad”. The login Data should be clean, no Duplicates should be there because this will break your functionality. It might return the duplicates and the count might not match the if statement that you will see later in this article. Double click you Button and add the following code in the Click event of the Button.

protected void btnlogin_Click(object sender, EventArgs e)

{



int Results = 0;

if (txtUsername.Text != string.empty && txtPassword.Text != string.empty)

{

Results = Validate_Login(txtUsername.Text.trim(), txtPassword.Text.trim());

if (Results == 1)

{

lblMessage.Text = "Login is Good, Send the User to another page or enable controls";

}

else

{

lblMessage.Text = "Invalid Login";

lblMessage.ForeColor = System.Drawing.Color.Red;

//Dont Give too much information this might tell a hacker what is wrong in the login

}

}

else

{

lblMessage.Text = "Please make sure that the username and the password is Correct";

}


}

Now our code is ready for testing. Run your Application and enter an incorrect password deliberately and see what message you see and when you enter the correct login you will receive a message that says

Login is Good, Send the User to another page or enable controls

In your application you can redirect the user to another page and store the Session that you will use through out your application And abondon when the user exit your application. Please note that for some application it is good to enable and disable Controls based on the Session value, meaning that you can check if the user is logged in , and display the benefits that logged in user can get in the same page. I will not explain more on that because it is beyong the scope of this article.

Conclusion


There are a lot of ways to do a login control in asp.net, but I thought it will be important to point the basic one to our users.

Thank you for visiting DotnetFunda

Vuyiswa Maseko

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:8 year(s)
Home page:http://www.Dotnetfunda.com
Member since:Sunday, July 06, 2008
Level:NotApplicable
Status: [Member] [MVP] [Administrator]
Biography:Vuyiswa Junius Maseko is a programmer and a moderator in ".NetFunda. Vuyiswa has been developing for 8 years now. his major strength are C# 1.1,2.0,3.0,3.5 and sql and his interest are in Silverlight,WPF,C#. He has been doing a lot of Silverlight development. He has been using .net since the beta version of it. He is also an online Trainer at www.Itfunda.com. Thanks to people like Sheo Narayan (.Netfunda) , Chris Maunder (codeproject), Colin Angus Mackay (codeproject), Dave Kreskowiak (Codeproject),.They have made vuyiswa what he is today.
 Responses
Posted by: Madhu.b.rokkam | Posted on: 23 Feb 2011 12:26:06 AM | Points: 25

You are right Vuyiswa.. Nice

Posted by: Vuyiswamb | Posted on: 23 Feb 2011 12:27:40 AM | Points: 25

:) Welcome

Posted by: Mahesh.d16 | Posted on: 08 Mar 2011 09:07:27 AM | Points: 25

thx man

Posted by: JimmyJohn | Posted on: 11 Mar 2011 09:05:14 AM | Points: 25

Hello i am getting an error...


Error 2 The type or namespace name 'sqlConnection' does not exist in the namespace 'System.Data.SqlClient' (are you missing an assembly reference?)

when i am trying your code...

i am using


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient.sqlConnection;
using System.Data;
using System.Drawing;

Please help....

Posted by: Vuyiswamb | Posted on: 11 Mar 2011 11:08:55 AM | Points: 25

You are using a wrong namespace.

change this

using System.Data.SqlClient.sqlConnection;


to this

using System.Data.SqlClient;


Thanks


Posted by: JimmyJohn | Posted on: 11 Mar 2011 12:17:36 PM | Points: 25

Ok i did it.... but my issue is... now ... even with the correct username and password in the TestData which i have it is taking me to the last else statement of wrong password/userid... ...

i have exactly copied what you have posted here i mean the code........ please advice ?

Posted by: JimmyJohn | Posted on: 11 Mar 2011 12:18:40 PM | Points: 25

SqlConnection con = new SqlConnection(@"Server=Local;Database=TestData;Trusted_Connection=True");


and is this correct for my local TestData (Database) located in APP_DATA Folder using windows Authentication ?

Posted by: Vuyiswamb | Posted on: 11 Mar 2011 12:48:27 PM | Points: 25

Do you have SQL install in your machine ? lets talk via gtalk vuyiswamb@gmail.com


Posted by: JimmyJohn | Posted on: 11 Mar 2011 12:56:26 PM | Points: 25

yes i have sql installed... like sql server 2005 .. and visual studio 2008... bro this is the project my manager has given me... i will add you !! tonite.. i am at work cannot use any third party mail accounts.. or voice chats... i will talk to you tonite... i appreciate your help brother....

Posted by: Eggy168 | Posted on: 14 Mar 2011 05:00:45 PM | Points: 25

Thanks for the information.
I have a minor issue in the SqlConnection section. I have the SQL 2008 Express install in the testing server, a Standard SQL 2005 in the actual server. I change my own data in this section, (@"User id=sa;Password=Dotnetfunda;Server=VUYISWA\VUYISWA;Database=Forum"); . However, I still have problem accessing it. Can I ask you how can I make it works?
Thanks.

Posted by: Vuyiswamb | Posted on: 15 Mar 2011 06:14:16 AM | Points: 25

what is the Error that you are getting ?

Posted by: Eggy168 | Posted on: 15 Mar 2011 12:38:07 PM | Points: 25

I do not know is it related to the SqlConnection problem. The error message is gone, but when I type the correct username and password (I double checked the SQL Server table), it has the "Invalid Login" message. May I ask what did I do wrong of the coding?
Thank you.

Posted by: Vuyiswamb | Posted on: 15 Mar 2011 04:06:40 PM | Points: 25

ok let me see your code

Posted by: Eggy168 | Posted on: 15 Mar 2011 04:45:54 PM | Points: 25

I have exactly the same code, except this piece,

 SqlConnection conn = new SqlConnection(@"User id=gigi; password=1234567890; server=LAPTOP_TOSHIBA\SQLXPRESS2008TOS;database=Budget_2011")


Username: user1
Password: password1

Thank you.

Posted by: Vuyiswamb | Posted on: 15 Mar 2011 05:16:59 PM | Points: 25

please send me a cs file and i will point the problem.

Posted by: Eggy168 | Posted on: 16 Mar 2011 01:51:17 PM | Points: 25

Can i have your email so I can send you the file? Thanks.

Posted by: Vuyiswamb | Posted on: 16 Mar 2011 06:00:17 PM | Points: 25

vuyiswamb at gmail dot com

Posted by: Eggy168 | Posted on: 21 Mar 2011 02:50:12 PM | Points: 25

I sent the file to your email. Thanks.

Posted by: Vuyiswamb | Posted on: 29 Mar 2011 01:51:12 AM | Points: 25

I did not see a problem with your code, let me do an example Project and i will send it to you

Posted by: Akiii | Posted on: 09 Jun 2011 06:07:05 AM | Points: 25

hi Vuyiswa sir,

the password is stored openly, i mean its not encrypted......can you tell me how to encrypt that and then store it ??

Thanks and Regards
Akiii

Posted by: Abhihits | Posted on: 06 Oct 2011 04:35:19 AM | Points: 25

Dear Sir,
Thankyou very much for this article but i am facing one problem. I always get message of 'Invalid Login' please tell me what is wrong here. It takes my too much time but still it is unresolved.
Waiting for ur reply.
Thankyou

Posted by: Aniruddh | Posted on: 09 Oct 2011 02:50:14 AM | Points: 25

hiiii Vuyiswamb

i need to discuss abt net topics.. so can we chat online if ur free ...can i add u in gmail ...????

Posted by: Nuwan | Posted on: 14 Nov 2011 12:37:46 AM | Points: 25

This is nice article. but i have a problem, how i control User & Administration permission in that login Example.
If you can please add some additional article foe control Normal user & Administrative privilege in login.

Posted by: Vuyiswamb | Posted on: 14 Nov 2011 01:22:29 AM | Points: 25

hi Nuwan

I have written an article that extends the capability of this article
http://www.dotnetfunda.com/articles/article1250-permission-module-or-security-module-in-aspnet-or-silverlight.aspx



Posted by: Nuwan | Posted on: 14 Nov 2011 02:18:29 AM | Points: 25

Hi Vuyiswamb,
Thanks for your Reply,
Is it possible to apply asp.net web application.
Because I never use to Silverlight.


Posted by: Vuyiswamb | Posted on: 14 Nov 2011 02:20:05 AM | Points: 25

The Structure of the Table is valid for all Technologies

Posted by: Hareesh | Posted on: 05 Jan 2012 08:05:06 AM | Points: 25

hi Vuyiswamb your article is nice. i got an error like Error 1 :The name 'lblMessage' does not exist in the current context. pls help me and how to resolve this error.


Posted by: Vuyiswamb | Posted on: 05 Jan 2012 08:38:18 AM | Points: 25

That is a Label, add a Label and name it "lblMessage"

Posted by: Hareesh | Posted on: 10 Jan 2012 07:40:04 AM | Points: 25

i got it.thanks for reply.

Posted by: Hareesh | Posted on: 10 Jan 2012 08:57:16 AM | Points: 25

thanks,i completed this task.

Posted by: Vuyiswamb | Posted on: 10 Jan 2012 09:25:34 AM | Points: 25

Glad to hear

Posted by: Jasmin | Posted on: 17 Jan 2012 03:05:00 AM | Points: 25

here, i got error.
please help me

lblmessage = ex.Message;

if (txtUsername.Text != "" && txtPassword.Text != "")

Posted by: Vuyiswamb | Posted on: 17 Jan 2012 03:30:34 AM | Points: 25

These are the names of the Controls

txtusername is the name of the Textbox for username and the txtPassword is the name of the Password textbox and "lblmessage " is the name of the message label. Look at these names in the code that i have provided in the code.


Posted by: Jasmin | Posted on: 17 Jan 2012 10:17:33 AM | Points: 25

one more error ,,
pls help me,,,,,,,,


if (Results == 1)
{
lblMessage.Text = "Login is Good, Send the User to another page or enable controls";
}
else

Posted by: Vuyiswamb | Posted on: 17 Jan 2012 01:16:54 PM | Points: 25


if(Results ==1)

{
Response.Redirect("AnotherPage.aspx",false);
}


Posted by: Taolut | Posted on: 04 Feb 2012 12:25:34 PM | Points: 25

Hi
I am v ery new to this programming and i was going to ask as im a bit confused, after creating the log in page, where do i put the validate login code, is it in thesame page as the log in interface page or somewhere else, help please. thanks

Posted by: Taolut | Posted on: 04 Feb 2012 12:55:17 PM | Points: 25

Found a way to fix the code and now i get invalid log in message, can you please help me

Posted by: Amarbide | Posted on: 22 Feb 2012 04:40:12 AM | Points: 25

hi
i cant able to connect to the database.when i enter username and password that i wrote in SQL,its showing invalid login..please help me

Posted by: Vuyiswamb | Posted on: 22 Feb 2012 07:11:28 AM | Points: 25

i see where you have a problem, i have Updated the Article



int Results = 0;


if (txtUsername.Text != string.empty && txtPassword.Text != string.empty)

{

Results = Validate_Login(txtUsername.Text.trim(), txtPassword.Text.trim());

if (Results == 1)

{

lblMessage.Text = "Login is Good, Send the User to another page or enable controls";

}

else

{

lblMessage.Text = "Invalid Login";

lblMessage.ForeColor = System.Drawing.Color.Red;

//Dont Give too much information this might tell a hacker what is wrong in the login

}

}

else

{

lblMessage.Text = "Please make sure that the username and the password is Correct";

}


Posted by: Amarbide | Posted on: 24 Feb 2012 03:16:02 AM | Points: 25

hi,
again error is coming ..
'string' does not contain a definition for 'empty'
'string' does not contain a definition for 'trim' and no extension method 'trim' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

please help me

Posted by: Amarbide | Posted on: 24 Feb 2012 03:24:53 AM | Points: 25

Got the solution of the above error..
but still showing invalid login..

Posted by: Rawsruffin | Posted on: 14 Mar 2012 02:48:15 PM | Points: 25

Hi, Amarbide and Vuyiswamb,
I was getting the same error so I changed the code by substituting "null" for "string.empty", shortening "txtUsername.Text.trim()" to "txtUsername.Text", and "txtPassword.Text.trim()" to "txtPassword.Text".

Yes, the code will build without errors. I'm using Visual Web Developer 2010 Express connected with my company's SQL Server connection string, which works fine. The problem is that I get "Invalid Login" even when I enter the correct credentials, e.g., Username: Vuyiswamb, Password: wwowididit.

Please let me/us know what could be the problem. I'll be happy to send you my .cs file via email if that's better.
Thank you!
RawsRuffin

Posted by: Shrona | Posted on: 31 Mar 2012 12:34:41 AM | Points: 25

As per this link :
http://www.dotnetfunda.com/articles/article808-how-to-write-a-simple-login-page-in-aspnet.aspx

In the above Stored Procedure we count the Records that have matched the Records and if there is one record found then it is a good login else it is a bad login. But how will you use this in your asp.net Page. First we have to create a Function that will access the stored procedure and call that function in click event of the button. Create a Function as show below in your page not inside your page load because you will get an Error.

public int Validate_Login(String Username, String Password)

{

SqlConnection con = new SqlConnection(@"User id=sa;Password=Dotnetfunda;Server=VUYISWA\VUYISWA;Database=Forum");

SqlCommand cmdselect = new SqlCommand();

cmdselect.CommandType = CommandType.StoredProcedure;

cmdselect.CommandText = "[dbo].[prcLoginv]";

cmdselect.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = Username;

cmdselect.Parameters.Add("@UPassword", SqlDbType.VarChar, 50).Value = Password;

cmdselect.Parameters.Add("@OutRes", SqlDbType.Int, 4);

cmdselect.Parameters["@OutRes"].Direction = ParameterDirection.Output;

cmdselect.Connection = con;

int Results = 0;

try

{

con.Open();

cmdselect.ExecuteNonQuery();

Results = (int)cmdselect.Parameters["@OutRes"].Value;

}

catch (SqlException ex)

{

lblMessage.Text = ex.Message;

}

finally

{

cmdselect.Dispose();

if (con != null)

{

con.Close();

}

}

return Results;

}

Should write it in source view of default.aspx or view code of default.aspx?
OR
should double click Login button and write this for button click event?



And one more doubt-> Does the code given by you here when used with C# to VB converter gives exact vb code as same as C# code?
Please reply soon.

Thank you in advance :)

Posted by: Vuyiswamb | Posted on: 31 Mar 2012 03:36:34 AM | Points: 25

hi all everyone who had a problem implementing this code please mail me and i will teamview to your machines to solve your problems,

vuyiswa[at]dotnetfunda.com

Posted by: Hariinakoti | Posted on: 11 Apr 2012 07:24:36 AM | Points: 25

hi ,
can u create login page in c#.

Posted by: Pappucha | Posted on: 21 Apr 2012 04:02:45 PM | Points: 25

Leads to an message Invalid login As i have given the correct USer name and Password .Could anu one of you please send me the code which is running proper so that i can have Cross check ...Else give me u r email id So that i can drop a mail .
And One more thing my program is Throwing NO error message ...Thats the only Help .....Waitiing For reply ...Email id rakeshchaubey1989@gmail.com

>> Write Response - Respond to this post and get points
Related Posts

Type Fundamentals

ASP.Net Dynamic Data is used to develop data driven web applications using dynamic page and field templates. In this article we will look into the custom routing mechanism supported by ASP.Net Dynamic Data.

This post is just a guide/approach for the bill desk payment gateway integration.

Till now we have not created any screen for data entry. In this tutorial we will create a simple data entry, flourish a simple model and display the model on a simple ASP.NET view.

In this article, I have tried to get the solution of checking a valid domain name in ASP.NET. This might not be the 100% full proof method to validate the valid domain however based on the number of test I did, it works.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/21/2012 7:57:31 AM