Click here to Skip to main content
Click here to Skip to main content

Generic Login Control

, 8 Jan 2005
Rate this:
Please Sign up or sign in to vote.
Generic Customizable login control for VB.NET Windows Forms.

Sample Image - Login_Control.jpg

Introduction

This is a control which will eases the work of creating the login form for Authentication.

Background

We see it is a tiresome work for creating the authentication form for the projects. This control has all the built in feature for validating the user. With this, we can use select query or Stored Procedures to validate a user from the Database (SQL Server 2000).

Setting it Up

First, after adding the control to the form, if you want to use stored procedures for validating the user, you can just select the following properties:

Selection Mode = StoredProcedure 
ConnectionString = server=ServerName\InstanceName;database=Databasename;user id=sa;
password=pass;min pool size=1; max pool size=100 
'(Please change to your servername/instancename, Userid and passoword )
StoredProcedureName = SP_ValidateLogin
UserIdParameter =@UserId
UserPasswordParameter = @UserPassword

or else if you want to use SelectQuery for validating the user, you can just select the following properties:

Selection Mode = SelectQuery
ConnectionString = _
   server=ServerName\InstanceName;database=Databasename;user id=sa;
password=pass;min pool size=1; max pool size=100 
'(Please change to your servername/instancename, Userid and passoword )
TableName = TBLUserTable
UserIdColumnName = vUser_LoginName
UserPasswordColumnName = vUser_Password

I have created two events for validating. One will get fired when the user exists and the other if the user does not exists.

The code is:

' Event is fired when the user exists and it will have 
'  the validated datarow so you can use this datarow for 
'  using in the application
' eg: User id, User Type ,.. etc.

Private Sub UcLogin_OnUserExists(ByVal drUserInfo As System.Data.DataRow) _
                                 Handles UcLogin.OnUserExists
  Try
    MessageBox.Show("Valid User", "Barathan Login Control", _
                 MessageBoxButtons.OK, _
                 MessageBoxIcon.Information)
  Catch ex As Exception
    MessageBox.Show("Error while Validating User", _
                 "Barathan Login Control", _
                 MessageBoxButtons.OK, MessageBoxIcon.Error)
  End Try

End Sub

' Event is fired when the user is invalid

Private Sub UcLogin_OnUserInvalid() Handles UcLogin.OnUserInvalid
  Try
    MessageBox.Show("Invalid User", "Barathan Login Control", _
          MessageBoxButtons.OK, _
          MessageBoxIcon.Information)
  Catch ex As Exception
    MessageBox.Show("Error while Validating User", "Barathan Login Control", _
          MessageBoxButtons.OK, MessageBoxIcon.Error)
  End Try

End Sub

That's it! You are done with authentication. This control is very easy to use.

The code

To raise events, I have declared two public events:

Public Event OnUserExists(ByVal drUserInfo As DataRow)

Public Event OnUserInvalid()

In this event, I have specified the delegate as Datarow for OnUserExists event. This may be useful for using the retrieved data.

Dim user_type as string = drUserInfo("UserType")

The actual code which raises these events are as follows:

' Logic : This is the Function that will be invoked to check the database 
Private Function CheckLogin() As Boolean 
  Try 
    If Me.SelectionMode = QueryType.SelectQuery Then 
      If Me.ExecuteSelectQuery = False Then 
        RaiseEvent OnUserInvalid() 
      End If 
    Else 
      If Me.ExecuteStoredProcedure = False Then 
        RaiseEvent OnUserInvalid() 
      End If 
    End If 
  Catch ex As Exception 
  End Try 
End Function

The code for validating the user login if the selection mode is set to StoredProcedure:

' Logic : This Will Execute the specified Stored Procedure 
'with the user id and password parameters

' and return true if user exists and false when not exists


Private Function ExecuteStoredProcedure() As Boolean
  Try
    Dim dsUser As New DataSet
    Dim Conn As New SqlConnection(Me.ConnectionString)
    Conn.Open()
    Dim myCmd As New SqlCommand(Me.StoredProcedureName, Conn)
    Dim PrmUserId As SqlParameter = myCmd.Parameters.Add(Me.UserIdParameter, _
         Me.TxtUsername.Text.ToString().Trim())
    Dim PrmPassword As SqlParameter = _
         myCmd.Parameters.Add(Me.UserPasswordParameter, _
    Me.TxtPassword.Text.ToString.Trim())
    myCmd.CommandType = CommandType.StoredProcedure
    Dim MyDa As New SqlDataAdapter(myCmd)
    MyDa.Fill(dsUser)
    Conn.Close()
    If dsUser.Tables(0).Rows.Count > 0 Then
      RaiseEvent OnUserExists(dsUser.Tables(0).Rows(0))
      Return True
    Else
      Return False
    End If
  Catch ex As Exception
    MessageBox.Show("Error While Executing the Stored Procedures", _
        "Executing Stored Procedure Error", _
        MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    Return False
  End Try
End Function

So finally, when clicking the Login button, the following code will check for valid properties and textboxes:

Private Sub btnlogin_Click(ByVal sender As System.Object, _
                   ByVal e As System.EventArgs) _
                   Handles btnlogin.Click
    Try
        If Me.CheckProperties = True Then
            If Me.CheckTextBoxes = True Then
                Me.CheckLogin()
            End If
        Else
            Me.Dispose() 'if Properties are not filled the application will exit.
            Application.Exit()
        End If
    Catch ex As Exception
        Throw ex
    End Try

End Sub

Stored Procedure

The Stored Procedure that I use to validate the login is:

    Create procedure dbo.LOGINSP_ValidateLogin
    @Userid varchar(50), 
    @UserPassword varchar(50) 
    as 
    BEGIN
        select  iUser_id as userid,
            vUser_LoginName LoginName,
            bUser_Main as Type
        from TBLUSERTABLE
        where     
            vUser_LoginName =@Userid 
            and vUser_Password=@UserPassword 
    END 

Next time, we will see the control with validating the user type also.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Barathan
Web Developer
United States United States
Senior Designer Analyst
C#, ASP.NET, ABAP
MCTS, MCPD, MCAD, MCP

Comments and Discussions

 
GeneralMy vote of 5 PinmemberH.Johnson24-May-11 3:29 
GeneralError while executing stored procedure [modified] Pinmemberesyone18-Jun-10 2:19 
Questionhi everyone PinmemberSpectrum school14-Feb-10 21:56 
GeneralLogin Control PinmemberMichael Wallis21-Apr-09 7:05 
Generallogin user control Pinmemberpooja mehta2-May-08 20:41 
Generallogin form Pinmembersrikanth goud11-Sep-07 23:14 
GeneralVB and access Pinmemberkickit3130-Nov-05 4:56 
GeneralYour Login Control PinmemberRock Solid24-Sep-05 7:14 
GeneralLogin Control Pinmemberkooljug11-Mar-05 20:58 
GeneralRe: Login Control PinsussBarathan12-Mar-05 1:46 
GeneralRe: Login Control Pinmemberkooljug22-Mar-05 18:00 
GeneralSQL PinsussAnonymous9-Jan-05 6:11 
GeneralRe: SQL PinsussBarathan9-Jan-05 17:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 8 Jan 2005
Article Copyright 2005 by Barathan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid