Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Simple login form example in asp.net Check Username and Password availability in database

Dec 8, 2011
Introduction

In this post I will explain how to implement simple login form using asp.net and I will explain how to Check Username and Password Exists in database using asp.net .

Description: 

One day I got mail from one of the reader he has asked about how to implement simple login form to check username and password details of user in database. If user details exist in database then we need to redirect user to welcome page otherwise we need to display “Invalid Username/Password”. Mostly it’s common for all the websites before access the website. I know that many of them feel it’s very easy but for the people who have started learning .NET they don’t know how to implement this because of that I decided to write post to help for the persons who is in need with this requirement. 

To implement this one first design table like this

ColumnName
DataType
UserId
Int(set identity property=true)
UserName
varchar(50)
Password
varchar(50)
FirstName
varchar(50)
LastName
varchar(50)

After completion of table creation enter some dummy data or use this link to create user registration form to insert userdetails in database.

Once data entered in table design your aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Login Form</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Username:
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"/>
<asp:RequiredFieldValidator ID="rfvUser" ErrorMessage="Please enter Username" ControlToValidate="txtUserName" runat="server" />
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<asp:TextBox ID="txtPWD" runat="server" TextMode="Password"/>
<asp:RequiredFieldValidator ID="rfvPWD" runat="server" ControlToValidate="txtPWD" ErrorMessage="Please enter Password"/>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
After that add the following namespaces in code behind

C# Code

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
After add namespaces write the following code in code behind

protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName =@username and Password=@password",con);
cmd.Parameters.AddWithValue("@username", txtUserName.Text);
cmd.Parameters.AddWithValue("@password", txtPWD.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if(dt.Rows.Count>0)
{
Response.Redirect("Details.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
}

VB.NET Code

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString)
con.Open()
Dim cmd As New SqlCommand("select * from UserInformation where UserName =@username and Password=@password", con)
cmd.Parameters.AddWithValue("@username", txtUserName.Text)
cmd.Parameters.AddWithValue("@password", txtPWD.Text)
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
If dt.Rows.Count > 0 Then
Response.Redirect("Details.aspx")
Else
ClientScript.RegisterStartupScript(Page.[GetType](), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>")
End If
End Sub
End Class

Here don’t forgot to set the connection string in web.config file here I am getting database connection from web.config file for that reason you need to set the connectionstring in web.config file like this

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings>
Demo


Download sample code attached


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

131 comments :

Anonymous said...

Nice artical... :)
Can u tell me how to access database if i am having its IP address & domain name??
thanks in advance.

Suresh Dasari said...

@leena...
if you want access database you need servername, userId and password also without these details i hope it's not possible to access database only with IP address and domain name..

name said...

Bro So so thanks.i watch your site dilly.

Your r perfect But you can do different type of Coding.

Anonymous said...

thanks bro..............

uyir said...

hey everything is working good, but while signing in it shows no error but didn't move to the redirection page , please guide me

uyir said...

sorry everything is worked fine . i found out my error , thanks for your tutorial , pls don stop

kranthi said...

its working

Anonymous said...

sir.. i got an SqlException was unhandled by the usercode error while running user registration form. plz help me sir.

vitthal khandke said...

asp .net login video

Anonymous said...

can youtell me how to implement the concept of seesion in this login page tso that unauthenticate user cant access

Anonymous said...

hey friend i want the same login page but with MS access.... and when i tried with MS access with valid connection code i can't find the "fill" in OleDb.DataReader.... pls provide me the code m waiting!!!

Anonymous said...

It was really awesome code.You can use session also in between your code then if any register user can login and it shows welcome to user........

Unknown said...

hi suresh i need to know how to make a login and registration page in asp.net with vb.net code and i have created my database in asp.net itself...
i tried to copy dis code but it is showing some errors

Zil said...

How to send verification email in localhost?

Anonymous said...

thanks

Ashish Khare said...
This comment has been removed by the author.
Ashish Khare said...

hii Sir,
i want to restrict to add same user name in database,
how can i??
and if exist then it so error msg "user name already exist"
plzz help me..

Unknown said...

Thanks you very much

Randika Vishman said...

Thanks Bro, it helps a lot!

Riwaz said...

Thanks bro.. But I want to have in 3 tier with data connection on data layer

Anonymous said...

I can also use the name of text box instead of @field name in select query, so what's the difference b/w them.

Anonymous said...

Hello Suresh!! can u help me to insert data using button in VB.Net with jQuery..im confused in this pls help me immediately

Anonymous said...

Thanks big time...
u saved my job

Unknown said...

when i logout the login page after i press back button page return previous page
what is the code page doesn't return back page
tarun

navya said...

thank u for sharing the articles.....

Niranjan said...

Thank you Sir

Ajay said...

hi sir
i want to create one connection class for all aspx.cs page for one application.
if is it possible please give me alink for this.

Unknown said...

hi sir,
i have connectivity problem from above code,
i cannot understand catlog,datasource in the sql connction.whenever i run above code i got below error
Warning 65 File 'Default.aspx.cs' was not found. and also i got error like missing of schema information pls give me solution for above problem

Revathy said...
This comment has been removed by the author.
Revathy said...

Server Error in '/login_and_registration_form' Application.
--------------------------------------------------------------------------------

Instance failure.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Instance failure.

Source Error:


Line 18: {
Line 19: SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
Line 20: con.Open();
Line 21: SqlCommand cmd = new SqlCommand("Select * from user where UserName=@username and Password=@password",con);
Line 22: cmd.Parameters.AddWithValue("@username",txt_UserName.Text);


Source File: g:\ASP.NET3.5\login_and_registration_form\Default.aspx.cs Line: 20



Hi,

I got the above error, but couldn't find why tat error came....i had properly put my connectionstring at web.config as per ur code.


kindly do the needful

Unknown said...

Dear sir,

I got some error during run at program

Exception Details: System.ArgumentException: No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.

SqlDataAdapter adf = new SqlDataAdapter(com);
DataTable td = new DataTable();
adf.Fill(td);
if (td.Rows.Count > 0)
{
Pleasae help me to solve out this error

regards,
Daya

Unknown said...

Dear sir,

Plese tell me How to see your valued Reply ?

Regards,

daya

Balaji said...

Nice and useful for me..

Unknown said...

Hi, My name is manish mayekar
I am just working on a web project created in visual studio 2010 with the help of asp.net as a front end and vb.net 2010 and sql server 2008 as back end
I tried to use DATE PICKER as you already posted on this site but it didn't show the Date Picker after clicking on the Text Box

I referred the following post which you posted on this site

JQuery Datepicker Example | jQuery Calendar Example with asp.net textbox
By: Suresh Dasari Apr 24, 2012
Categories: Asp.net, DatePicker, General, JQuery

Unknown said...

Hi, My name is manish mayekar
I am just working on a web project created in visual studio 2010 with the help of asp.net as a front end and vb.net 2010 and sql server 2008 as back end
I tried to use DATE PICKER as you already posted on this site but it didn't show the Date Picker after clicking on the Text Box

I referred the following post which you posted on this site

JQuery Datepicker Example | jQuery Calendar Example with asp.net textbox
By: Suresh Dasari Apr 24, 2012
Categories: Asp.net, DatePicker, General, JQuery

Spotlight Spectator said...

Hello

Is there a way that i can see my credintials on the other page to show what i put in the fields for confirmation and when i press agree there then it will take me to other page ?

powermaster said...

explain how to make a class file to insert data into database ????

Unknown said...

thanks for your code and explanation.

have one question everything is working fine,i want to redirect user to a page and show his information on the page.

can you please help me

Unknown said...

really soooperb work.......

Unknown said...

Hi Suresh,

I m fresher for the ASP.NET. I dont know how to create Stored Procedure. Can you please provide necessary steps. Awaiting for your reply...................

Ami Desai said...

hii..Suresh can u help to make my project

Anonymous said...

HI Suresh,

May I first compliment you on such a very informative and most beneficial site.

I tried out your code (VB), and I got several errors.

1) At Dim con As New, I got a blue wiggly line at NEw with the error message "Type expected".

2) Blue wiggly line also appears at SQLCOnnection with the error message "SqlCOnenc tion is a type and cannot be used as an expression.

3) Blue wiggly line also appear at con.Open(), where con was said have not been declared.

I am coming from a non-IT background, trying to experience how to write a program, and your advice is deeply and very much appreciated.

Thank you in advance.

From,
Lam

Anonymous said...

please can u tell me! when i execute the above code using c# it gives error message 'must declare @username scalar' now what to do?

Unknown said...

hi ,
i have datetimepicker and listbox (3). here i have select datatime picker the particular date. then listboxi shows empid, listbox2 and
listbod3 show employee login time and logout time. listbox2 shows
particular date. here one problem occur. full night shift entry problem.
for example empid = 1510004 login : 11:55pm logout : 7.23 AM
so login time shows listbox2, logout tiem shows listbox3. how to calculate work duration between this . ple help me

Anonymous said...

hi

I tried to paste the coding but not able to post.

Bheesham kumar Sharma said...

can u plz explane this code....i am startup learner in asp.net

Unknown said...

hi ,
i have datetimepicker and listbox (3). here i have select datatime picker the particular date. then listboxi shows empid, listbox2 and
listbod3 show employee login time and logout time. listbox2 shows
particular date. here one problem occur. full night shift entry problem.
for example empid = 1510004 login : 11:55pm logout : 7.23 AM
so login time shows listbox2, logout tiem shows listbox3. how to calculate work duration between this . ple help me. if any one know ple replay

Anonymous said...

Shata maaraya

anbarasan said...

I can't understand your coding.I want explanation for that............

Unknown said...

1shift time : 7 am to 4 pm
2shift time : 4 pm to 12 am
3shift time : 12 am to 7 am.
day shift no problem, 2shift and 3rd shift only problem.
datetimepicker => selected date

listbox1 => empid

listbox2 => employee login and logouttime

listbox 3 => login and logout.

problem1 :
2shift employee go to 3.55 pm to 11:55pm here no problem but
3.55pm to 12.04 am work duration calculation between this ? here only problem

another 2:

3shift employee go to 11.55 pm to 7.00am and
12.04 am to 7.05 am . this is the problem work duration calculation between this. here i m using the code for vb6.0.. kindly help me. or send the code my mail id :boomsnsiva@gmail.com

Unknown said...

We have 3listbox . and one timepicker and 2 label.
1 => timepicker is date only selected . ex ( 01/01/2013)
2 => listbox1 have empid . ex(1510004)
3 => label 1 is empid
4 => label 2 is empname
5 => listbox2 is employee login & logout (current date and time)
6 => listbox3 is employee login & logout (tommorow date and time)
7 => here 3 shift going on
i) IShift time : 7.00 am to 4.00pm
ii) IIShift time : 4.00pm to 12.00pm
iii) IIIShift time : 12.00am to 7.00am
8 => here ishift no problem ( 7.00 am to 4.00 pm no problem samedate)
9 => IIShift is start time 4.00 pm.but employee login time before
3.45 pm to 11.55pm or 12.05 am
10 => IIIShift is start time 12.00am to 7.00 am.but here employee
Login time 11.55pm or 12.05am to 7.05 am


So here I need to IIShift and IIIShift time. Calculate between this .
Listbox2 have intime and listbox3 have outtime . one in and one out . what is code for vb form.
II SHIFT TIME:

01/01/2013
3.55 pm

12.05 am




I need work duration betweent this . in vb form .Here date 01/01/2013 is is intime and outtiem is 02/01/2013.















IISHIFT TIME:

01/01/2013 :


11.55 PM







07.10 am


SUPPOSE employee login 12.01 am to logout 07.12 am . so I need also


01/01/2013 02/01/2013


Today date and time
12.05 am
07.12 am

Here employee login next date and time . so have to calculate between this .what
About the today date . what is duration between this . here I mention following the code . please help me .






Anonymous said...

thank's for giving this in so simple, easy and right way

you have any site where i find this type of all easy answer
because i am a fresher now, and i struggling so much

Birendra said...
This comment has been removed by a blog administrator.
Premkumar said...

i need code to display alert to the user "Register successfully" before redirect code execute..

Unknown said...

I need code to display image sliding in masterpage or masterpage selected .aspx page

ramesh.j said...

Iam not getting image as out in gridview its not showing image in gridview

Unknown said...

How to verify user id and password by using ms access in asp.net. Thanks in advance

sandeep said...

hi suresh,
i need a code that enters userid and password from database to login page to respective username and password and press login..hence this concept is nothing but single sign on. plz help me and send me code in java..

Anonymous said...

Thanxx for d help...

Anonymous said...

Very useful

Anonymous said...

How can you make sure that a user simly doesn't just type in "Details.aspx" in the browser to skip the loginpage?

Is that a way to stop this kind of behaviour?

Unknown said...

Good afternoon,

I am trying to make this work, but for some reason it's always saying that my username and password combination is incorrect..

I have double and triple checked my credentials, ran the query with my credentials in SQL Management Studio and it returns the results just fine.

Can you please shed some light on this?

Thanks, Robert.

Baibhav Singh said...

thanks for the help....

Anonymous said...

thank you but my question is i have mail Id and username I register on one site after some day i forgot my registration and i register myself once again that time i enter my same id and email address after i enter and click register button i have get warning how can i implement that type code

Unknown said...

If i logout from website.when i click on back button it will again redirecting to the back page..how to solve this problem.can u explain me

lockpop said...

i want deploy my window application with sql server database ..... on other computer ... do other computer need sql sever on them .. please tell all about deployment .... i m stuck .... my ID is :: lockpop007@gmail.com

Unknown said...

Worked Perfectly fine. Thank you !

Nikitha said...

Thanks

Unknown said...

hi , i have created a webform and hosted also i have credentials,server name everything and i can login also but how to check the web form data submitted by user...please help me.

AVANEESH SOFTWARE said...

thanks

Mukesh said...

You are a great my fellow bro, Really this blog is a house of coding, skills and much more... cool blog dude :) ...keep posting...thanks

Anonymous said...

Thank you for your valuable Answer

sindhu said...

Hello sir,
your coding is very helpful for me,... thank you so much. It's a good job, pls continue it. sir i have 1 dout, is it a good practice to give the values for userid and password directly in the database or through coding. pls give me the reason for it...

Manjari Bhatnagar said...

thanks a tonn..mindblowing job...

Unknown said...

hello sir,
i want store pdf file in database and show it on web application as image. when i click image then pdf file should open in new page. i am using asp.net & sql server 2008 .
please please help me sir . how i will do.

Govind

অবান্তর e-পত্রিকা said...

how to introduce the KEEP ME LOGGED IN feature..please explain

Anonymous said...

Sir G..........u r ultimate guy

ankit sahu said...

sir your login code not working giving this error
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Anonymous said...

Thanks and very useful.....

Anonymous said...

Thank you very much Sir!
I have been trying to solve this for 2 weeks.

Jessy said...

Thank you Sir,

may I ask.. how to make the pop up message like "Username is blank"?

sir do you have any C# custom required field validation guide? C# coding validation.

vivek said...

hi sir how to connect c# project in my sql

Anonymous said...

Sir plz help me with this error....

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0246: The type or namespace name 'DataTable' could not be found (are you missing a using directive or an assembly reference?)

Source Error:


Line 21: cmd.Parameters.AddWithValue("@password", txtPWD.Text);
Line 22: SqlDataAdapter da = new SqlDataAdapter(cmd);
Line 23: DataTable dt = new DataTable();
Line 24: da.Fill(dt);
Line 25: if(dt.Rows.Count>0)

Source File: c:\Users\cs\Desktop\WebSite3\Login.aspx.cs Line: 23

Anonymous said...

Thanks a lot. It was very helpful.

Unknown said...

gr8..but how can we add session to it?

Unknown said...

Hi your all tutorials are superb they contain all the explanation.i need your help in making admin panel can you plz provide the tutorial that explain it thoroughly

Anonymous said...

Hi sir. Really i am saying your samples are very good. I am interested to learn more about .net sir. I have seen examples but some code i cant understand sir. Me fresher, so kindly tell me the what i want to do first sir. Please give me some explained examples.

Lionking said...

Can someone please help me with a problem I am facing. I have to keep myself logged in in a website continously so as to remain connected to internet. I would like to have a code which does these things in sequence
1. Ping google.com at a decided interval by me for checking my connectivity with internet.
2. If connected to internet, no action however if not connected then take me to the login form of my ISP
3. Insert my username & password and relogin
4. check again if connected to internet..(basically take me back to sl no 1)

Unknown said...

Thanks Suresh...

Unknown said...

Hi sir. i want help sir . how did edit ,delete,update in gridview data .... help sir //...

Unknown said...

sir another question how to set only outline border sir, now am in fresher help me with basic procedure sir ......

Anonymous said...

code does not work properly .exception like
The ControlToValidate property of 'RequiredFieldValidator1' cannot be blank.
help me to solve it.

Unknown said...

how to generate password automatically and use the generate password to access or login in asp.net c#.

Anonymous said...

Very valuable article .. Thanks.. but facing two errors in vb code:
1. Type expected error in Dim con as new
2. sql connection is a type and cannot be used as an expression

Thanks in advance
Amit

Anonymous said...

Thankyou

Web Developer Surat said...

Excellent work 4 all..............

Android Development India said...

Thanks. This will help a lot.

Anonymous said...

sonu asati

thanks .............

Unknown said...

Sir, Thank you so much for ur tutorials. It really help me :-)

Anonymous said...

hello i want code for logout

Unknown said...

Thanx....

Ba la ji said...

what is exception handling

Unknown said...

i change my password.it show ur old password is incorrect.but old password correct what the reason

Unknown said...

Dear sir
I am Very Very Thank Full To You

BE UNIQUE said...

ClientScript.RegisterStartupScript(Page.GetType(), "validation", "script language='javascript'alert('Invalid Username and Password')/script");
dude can u explain tis script

Unknown said...

helpfull

admin2 said...

hi
plzzzzz programming LOG OUT button , and use session ,, and solve browser back button ,,, plzzzz

thank you

Anonymous said...

Hi
Thank alot
Dear sir wich code i should use in my other admin pageload?
i am waiting you.

ambi said...

thanks

Anonymous said...

please write the stored procedure for this Article

Unknown said...

Great Job Done!!!

Unknown said...

where the javascript?? it take all i.d ...even it wrong...at localhost....it's not wrok proper...

Anonymous said...

connection close code line,
disposing dataset object ????? not required .. .

Unknown said...

i having error while run this code...can u help me
Server Error in '/' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 24: protected void btnSubmit_Click(object sender, EventArgs e)
Line 25: {
Line 26: SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
Line 27: con.Open();
Line 28: SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName =@username and Password=@password", con);

Anonymous said...

Line 20: {
Line 21: SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MFundPOCConnectionString"].ConnectionString);
Line 22: con.Open();
Line 23: SqlCommand cmd = new SqlCommand("select * from empkeni where ename=@username and pwd=@password", con);
Line 24: cmd.Parameters.AddWithValue("@username", txtUserName.Text);

------------------------------------------------------------------------------------------------------------

{"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"}

error at Line: 22

bits said...

sir, Very Helpfull article but how to confirm the new user through E-mail verification,sir please provide the code for this

Unknown said...

awesome bro

Unknown said...

sir how to can we see username in welcome page we are using windows asp.net and sqlserver 2008 plz tell me sir

Unknown said...

Please where do i specify the Database Name and table in the code behind and webconfig file

kannan said...

how to view the particular persons details who is logged in the website by using session asp.net

Unknown said...
This comment has been removed by the author.
jignesh kadvani said...

Hi... coding works fine... but one problem is that username and password check is not case sensitive. if i store username=ADMIN and password=ADMIN in the database and when i pass value from the form in lowercase then also it redirects to the otherpage. which should not be happend. so is there any way to make case sensitive query... or table.

Anonymous said...

How it display the message "Welcome to our sample site" after clicking submit button?

Hari said...

How it display the message "Welcome to our sample site" after clicking submit button?

Unknown said...
This comment has been removed by the author.
Unknown said...

Hiii
Invalid column name 'UserName'.
Invalid column name 'Password'.

Error come

Unknown said...

how to use hosted sql server database in Android app

Anonymous said...

hello sir,i am new to coding.can you explain me each line in detail.so that i can learn things quickly.

Anonymous said...

hi

Anonymous said...

with out database how to set username and password please help me

Computer Science Tutorial said...

good one Suresh

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.