Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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:
Total page views :  60989
Total downloads :  1202
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
VB.NETLoginControl.zip
 
Become a Sponsor

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.


Login to add your contents and source code to 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 7 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.

Rach him at raj2511984@yahoo.com OR 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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 
feedback by ashish On June 30, 2009
thanks for your programming concept


   
Reply | Email | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 
ok by Ferry On March 23, 2010
ok
Reply | Email | Delete | 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 | Delete | 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 | Delete | Modify | 
Re: focus on username by Raj On June 7, 2010
can u write in english?? i can not understand this language.
Reply | Email | Delete | 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 | Delete | Modify | 
Re: Re: Re: focus on username by Fabrizio On June 14, 2010
HELP ME!!!!!
Reply | Email | Delete | Modify | 
nice job by abraham On August 3, 2010
I really thank you . It has beeb helping me much.
Thanx once again
Reply | Email | Delete | Modify | 
ASP.Net 4 Hosting is here
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.