Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » ASP.NET and Web » Login Control in ASP.NET 3.5 using VB.NET

Login Control in ASP.NET 3.5 using VB.NET

In this article, I am going to discuss how to use Login control in ASP.NET 3.5 using VB.NET step by step.

Author Rank :
Page Views : 93945
Downloads : 1857
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
VB.NETLoginControl.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

The ASP.NET login controls provide a robust login solution for ASP.NET Web applications without requiring programming. By default, login controls integrate with ASP.NET membership and forms authentication to help automate user authentication for a Web site. It provides you with a ready-to-use user interface that queries the user name and password from the user and offers a Log In button for login. It validate user credentials against the membership API and encapsulating the basic froms authentication functionality like redirecting back to the original requested page in a restricted area of you application after the successful login.

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.

Note - Login controls might not function correctly if the Method of the ASP.NET Web page is changed from POST (the default) to GET.

  • Start Microsoft Visual Studio 2008
  • Create a new ASP.NET WebSite using Visual Basic, Like this:



  • Drag and drop Login control on page from ToolBox.





    Figure 1.

Whenever user hits the Log In button, the control automatically validates the user name and password using the membership API function Membership.ValidateUse() and then calls FormAuthentication.redirectFromLoginPage() if the validation was successful. All options on the UI of the LoginControl affect the input delivered by the control to these methods. For Example, if you click the "Remember me next time" check box, it passes the value true to the createPresistentCookie parameter of the RedirectFromLoginPage() method. Therefore, the FormAuthenticateModule creates a persistent cookie.

There are three Login Tasks by default.

  • Auto Format - you can select default schemes.
  • Convert To Template - You can edit content of Login Control.
  • Administer Website -  You can configure Web Site Administration Tools, Like Security, Application, Provider.

 

Figure 2.

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

<div>

<asp:Login ID="Login1" runat="server" BackColor="#F7F7DE" BorderColor="#CCCC99" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="10pt">

<TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

</asp:Login>

    </div>

    </form>

You can change styles of LoginControl using css too,  Like this:

.LoginControl

{

          background-color:#F7F7DE;

          border-color:#CCCC99;

          border-style:solid;

    border-width:1px;

    font-family:Verdana;

    font-size:10px;    

}

And now apply css to control:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Login Control</title>

    <link href="StyleSheet.css" type="text/css" rel="Stylesheet" />

</head>

<body>

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

    <div>

        <asp:Login ID="Login1" runat="server" CssClass="LoginControl">

            <TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

        </asp:Login>

    </div>

    </form>

</body>

</html>

If you running the page and if the CSS file is placed in a directory where anonymous access is denied, the add the following configuration for the CSS file to you web.config file. 

<location path="StyleSheet.css">

<system.web>

<authorization>

<allow users="*"/>

</authorization>

</system.web>

</location> 

You can add several hyperlinks to your Login control, such as hyperlink to a help text page, or a hyperlink to to a registration page.

<asp:Login ID="Login1" runat="server" CssClass="LoginControl"

CreateUserText="Register"

CreateUserUrl="~/Register.aspx"

HelpPageText="Additional Help" HelpPageUrl="~/Help.aspx"

InstructionText="Please enter your user name and password for login.">

<TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

</asp:Login>

Looks like this :

Here is .VB Code:

Imports System

Imports System.Collections.Generic

Imports System.Linq

Imports System.Web

Imports System.Web.UI

Imports System.Web.UI.WebControls

Imports System.Data.SqlClient

 

Partial Class _Default

    Inherits System.Web.UI.Page

 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not Me.IsPostBack Then

            ViewState("LoginErrors") = 0

        End If

    End Sub

 

    Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As AuthenticateEventArgs)

        If YourValidationFunction(Login1.UserName, Login1.Password) Then

            ' e.Authenticated = true;

            Login1.Visible = False

            MessageLabel.Text = "Successfully Logged In"

        Else

            e.Authenticated = False

        End If

    End Sub

 

    Protected Sub Login1_LoginError(ByVal sender As Object, ByVal e As EventArgs)

        If ViewState("LoginErrors") Is Nothing Then

            ViewState("LoginErrors") = 0

        End If

 

        Dim ErrorCount As Integer = CInt(ViewState("LoginErrors")) + 1

        ViewState("LoginErrors") = ErrorCount

 

        If (ErrorCount > 3) AndAlso (Login1.PasswordRecoveryUrl <> String.Empty) Then

            Response.Redirect(Login1.PasswordRecoveryUrl)

        End If

    End Sub

 

    Private Function YourValidationFunction(ByVal UserName As String, ByVal Password As String) As Boolean

        Dim boolReturnValue As Boolean = False

        Dim strConnection As String = "server=.;database=Vendor;uid=sa;pwd=wintellect;"

        Dim sqlConnection As New SqlConnection(strConnection)

        Dim SQLQuery As String = "SELECT UserName, Password FROM Login"

        Dim command As New SqlCommand(SQLQuery, sqlConnection)

        Dim Dr As SqlDataReader

        sqlConnection.Open()

        Dr = command.ExecuteReader()

        While Dr.Read()

            If (UserName = Dr("UserName").ToString()) And (Password = Dr("Password").ToString()) Then

                boolReturnValue = True

            End If

            Dr.Close()

            Return boolReturnValue

        End While

        Return boolReturnValue

    End Function

End Class

If you insert wrong username and password then message will show like this:

If you insert correct usename, password then redirect your page whereever you want or you can show message in ErrorLabel like this:

I am attaching my database with application in App_Data folder, if u want to use my database then attach my .MDF file.

Any question and queries ask me any time.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Raj Kumar

Raj Kumar is a Microsoft MVP and Senior Software Engineer with lots of hands on experience using ASP.NET 2.0/3.5, AJAX, MVC, C#, Visual Basic .NET, SQL Server 2005/2008, Oracle, WPF, WCF, XAML and Silverlight. He has over 6 years of IT experience working most on Microsoft technologies. He holds Master's degree in Computer Science. When he is not writing code, he likes to write articles and play cricket.

Reach him at raj2511984@gmail.com 

 

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Error by fateemah On October 23, 2008
Hello, I have been trying to implement the above code but have been met with quite a few problems Firstly, the Imports are not accepted and secondly, i keep on getting the error message " reference to a non shared reference requires an object reference" for "Login1" which is underlined in blue in this part of the code:- Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As AuthenticateEventArgs) If YourValidationFunction(Login1.UserName, Login1.Password) Then ' e.Authenticated = true; Login1.Visible = False MessageLabel.Text = "Successfully Logged In" Else e.Authenticated = False End If End Sub Please help me if possible...I am pretty stuck with this problem and really need help thanks
Reply | Email | Modify 
solution by Urielz On November 24, 2008
Hello, fateemah: This error happens because surely you have a LOGIN control within a LOGINVIEW control. I have had the same error. I solved this by seeking LOGIN control within the LOGINVIEW control. Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As AuthenticateEventArgs) Dim objLogin As System.Web.UI.WebControls.Login = CType(LoginView1.FindControl("Login1"), System.Web.UI.WebControls.Login) If YourValidationFunction(objLogin.UserName, objLogin.Password) Then e.Authenticated = True objLogin.Visible = False MessageLabel.Text = "Successfully Logged In" Else e.Authenticated = False End If End Sub I hope you will help
Reply | Email | Modify 
Smart tag content! by Naive On May 12, 2009
Hi there. I have a question. Previously, in Visual Studio 2005, login control had template editing; such as "logged in" template, "anonymous" template, etc. These were available through the smart tag. What happened to those?!
Reply | Email | Modify 
Re: Smart tag content! by Raj On May 16, 2009
may be something wrong with your visual studio. i can see in my visual studio and that is LoginStatus control not Login control.
Reply | Email | Modify 
Smart tag content! by Sindhu On August 18, 2010
Hi,

Can u please explain the entrire login controls along with source code.(i.e) codes for password recovery,change password etc.,

Thank you.
Regards,
SindhuViswanathan
Reply | Email | Modify 
feedback by ashish On June 30, 2009
thanks for your programming concept


   
Reply | Email | Modify 
About Login Controls by Bonu On July 11, 2009
sir can you expalin the usage of login controls like forget password , recovery passwor and new user sign up
Reply | Email | Modify 
about connection??? by ahmad On October 16, 2009
sir, i found this error         sqlConnection.Open()
could u help me, why this happen???
maybe there are step by step for manage the database....
what do u think about this?

thanks before
Reply | Email | Modify 
Login by moreshwar On November 15, 2009
Installed VS 2010 Professional beta 2. The Site Master page has already a login control.
Would like to know how to write the class and using Sql 2008 to create append edit update delete data regarding username password mailAddress and more some fields 
Reply | Email | Modify 
Just able to read first row in Table: Login by Mutia On January 21, 2010

hi,, i can log in successfully, but i have to attach the database "Vendor" in folder "Data" under SQL Server 2005 n modify the uid n password.

But i realize that your program is only able to verify 1 row in the database (which is UserName "raj" and Password "raj" that in the first row). When I add another row(eg. UserName "name", Password "pw") and after that i try to reLogin using the second row besides "raj", the system will say that i put the wrong username n password.
Can u provide the solution so that the system read all data in the table, not only the first row?
Thank you

Reply | Email | Modify 
asp.net login article and code by emmie On February 10, 2010
This is exactly what I needed, thanks! Great article and the sample code is a perfect starting point for a novice like me.
Reply | Email | Modify 
ok by Ferry On March 23, 2010
ok
Reply | Email | Modify 
asp.login Username and Password by Ray On March 24, 2010
I require to have a login form on my guestbbook.aspx page, to open the guestbook enter form. I have inserted asp.login. I have studied Raj's code, but can't seem to find where to store the Username and  Password. Help would be appreciated

Ray   
Reply | Email | Modify 
Re: asp.login Username and Password by eltjo On September 3, 2010
Same Problem Here   Can only Login with the Credentials of the first Row   
Reply | Email | Modify 
focus on username by Fabrizio On June 3, 2010
Ciao sono un developer italiano e sono alle prime armi con il login control.
Come posso attivare la funzione "focus" sulla textbox "UserName" sull'evento Page_Load? Facendo Login1.UserName.Focus() genera errore. Come dovrei impostarlo??
Reply | Email | Modify 
Re: focus on username by Raj On June 7, 2010
can u write in english?? i can not understand this language.
Reply | Email | Modify 
Re: Re: focus on username by Fabrizio On June 7, 2010
Ok I'll translate it even if I'm not good with English:
Hello, I am an Italian developer and beginners with the login control.
How do I activate the "focus" on the textbox "UserName" on Page_Load event?
If I use Login1.UserName.Focus() there is error. How should I set?
Reply | Email | Modify 
Re: Re: Re: focus on username by Fabrizio On June 14, 2010
HELP ME!!!!!
Reply | Email | Modify 
nice job by abraham On August 3, 2010
I really thank you . It has beeb helping me much.
Thanx once again
Reply | Email | Modify 
Checking that user got to webpage via legal login? by meir On August 6, 2011
Hi Loved the article and the code. One small issue I'd like if you could explain in more detail how to test that the user got to the webpage only after a successful login?? Regards Meir
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.