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

Simple login form example in Check Username and Password availability in database

Dec 8, 2011

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


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

Int(set identity property=true)

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="">
<head runat="server">
<title>Login Form</title>
<form id="form1" runat="server">
<asp:TextBox ID="txtUserName" runat="server"/>
<asp:RequiredFieldValidator ID="rfvUser" ErrorMessage="Please enter Username" ControlToValidate="txtUserName" runat="server" />
<asp:TextBox ID="txtPWD" runat="server" TextMode="Password"/>
<asp:RequiredFieldValidator ID="rfvPWD" runat="server" ControlToValidate="txtPWD" ErrorMessage="Please enter Password"/>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
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);
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();
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");


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)
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()
If dt.Rows.Count > 0 Then
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

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

Download sample code attached

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

Get the latest,, 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


Anonymous said...


leena206 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...

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..

Anonymous said...


sundar neupane said...

Bro So so thanks.i watch your site dilly.

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

adil khokar 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

priya 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........

ammarah khalid said...

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

Zil said...

How to send verification email in localhost?

Anonymous said...


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..

German Alex said...

Thanks you very much

Randika Vishman said...

Thanks Bro, it helps a lot!

Riwaz Bhandary 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 confused in this pls help me immediately

Anonymous said...

Thanks big time...
u saved my job

Tarun Kumar 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

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.


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


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

Daya Korat 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();
if (td.Rows.Count > 0)
Pleasae help me to solve out this error


Daya Korat said...

Dear sir,

Plese tell me How to see your valued Reply ?



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 as a front end and 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 textbox
By: Suresh Dasari Apr 24, 2012
Categories:, 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 as a front end and 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 textbox
By: Suresh Dasari Apr 24, 2012
Categories:, DatePicker, General, JQuery

Zeeshan Naqi said...


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 ?

abinash pujhari said...

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

shashank pohare 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

vicky varane said...

really soooperb work.......

vicky varane 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 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.


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?

siva nagendran 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...


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

My Thoughts by Bheesham kumar sharma said...

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

siva nagendran 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............

siva nagendran 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

siva nagendran 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.

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.


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..

sagar gosai 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

Abdul Kalam said...

How to verify user id and password by using ms access in 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?

Rob de Jonge 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

Vinod Banavath said...

If i logout from website.when i click on back button it will again redirecting to the back 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 ::

Sridhar K7 said...

Worked Perfectly fine. Thank you !

Nikitha said...


Aqhib Javeed 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.



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...

Govind Singh 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 & sql server 2008 .
please please help me sir . how i will do.


atanu chatterjee 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.

shaan banka said...

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

Shilpa Mittal 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 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)

Kishor Kulkarni said...

Thanks Suresh...

karthikeyan nagarajan said...

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

karthikeyan nagarajan 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.

alexander chawang said...

how to generate password automatically and use the generate password to access or login in 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

Anonymous said...


Web Developer Surat said...

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

Android Development India said...

Thanks. This will help a lot.

Anonymous said...

sonu asati

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

Shanawaj Alam said...

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

Anonymous said...

hello i want code for logout

Pramod Kumar said...


Ba la ji said...

what is exception handling

Rajesh Srm said...

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

rath ajit 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

Pankaj Sen said...


admin2 said...

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

thank you

Anonymous said...

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

Give your Valuable Comments

Other Related Posts

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