Click here to Skip to main content
15,885,278 members
Articles / Desktop Programming / Windows Forms
Article

Generic Login Control

Rate me:
Please Sign up or sign in to vote.
2.53/5 (15 votes)
8 Jan 20051 min read 174.6K   3K   53   13
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:

VB
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:

VB
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:

VB
' 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:

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

VB
Dim user_type as string = drUserInfo("UserType")

The actual code which raises these events are as follows:

VB
' 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:

VB
' 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:

VB
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:

SQL
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


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

Comments and Discussions

 
GeneralMy vote of 5 Pin
H.Johnson24-May-11 3:29
H.Johnson24-May-11 3:29 
GeneralError while executing stored procedure [modified] Pin
esyone18-Jun-10 2:19
esyone18-Jun-10 2:19 
Questionhi everyone Pin
Spectrum 214-Feb-10 21:56
Spectrum 214-Feb-10 21:56 
GeneralLogin Control Pin
Michael Wallis21-Apr-09 7:05
Michael Wallis21-Apr-09 7:05 
Generallogin user control Pin
pooja mehta2-May-08 20:41
pooja mehta2-May-08 20:41 
Generallogin form Pin
srikanth goud11-Sep-07 23:14
srikanth goud11-Sep-07 23:14 
GeneralVB and access Pin
kickit3130-Nov-05 4:56
kickit3130-Nov-05 4:56 
GeneralYour Login Control Pin
Mark 824-Sep-05 7:14
Mark 824-Sep-05 7:14 
GeneralLogin Control Pin
kooljug11-Mar-05 20:58
kooljug11-Mar-05 20:58 
GeneralRe: Login Control Pin
Barathan12-Mar-05 1:46
Barathan12-Mar-05 1:46 
GeneralRe: Login Control Pin
kooljug22-Mar-05 18:00
kooljug22-Mar-05 18:00 
GeneralSQL Pin
Anonymous9-Jan-05 6:11
Anonymous9-Jan-05 6:11 
GeneralRe: SQL Pin
Barathan9-Jan-05 17:03
Barathan9-Jan-05 17:03 

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

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