65.9K
CodeProject 正在变化。 阅读更多。
Home

通用登录控件

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.53/5 (15投票s)

2005年1月8日

1分钟阅读

viewsIcon

176702

downloadIcon

3027

适用于 VB.NET Windows Forms 的通用可定制登录控件。

Sample Image - Login_Control.jpg

引言

此控件将简化创建身份验证登录表单的工作。

背景

我们看到为项目创建身份验证表单是一项繁琐的工作。此控件具有所有内置功能来验证用户。使用此控件,我们可以使用 SELECT 查询或存储过程从数据库(SQL Server 2000)验证用户。

设置

首先,将控件添加到表单后,如果想使用存储过程来验证用户,可以选择以下属性:

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

或者,如果想使用 SelectQuery 来验证用户,可以选择以下属性:

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

我创建了两个事件来进行验证。一个事件将在用户存在时触发,另一个事件将在用户不存在时触发。

代码是:

' 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

完成了!您完成了身份验证。此控件非常易于使用。

代码

为了触发事件,我声明了两个公共事件:

Public Event OnUserExists(ByVal drUserInfo As DataRow)

Public Event OnUserInvalid()

在此事件中,我将委托指定为 Datarow 用于 OnUserExists 事件。这对于使用检索到的数据可能很有用。

Dim user_type as string = drUserInfo("UserType")

触发这些事件的实际代码如下:

' 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

如果选择模式设置为 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

因此,最后,单击“登录”按钮时,以下代码将检查有效的属性和文本框:

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

存储过程

我用来验证登录的存储过程是:

    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 

下次,我们将看到带有用户类型验证的控件。

© . All rights reserved.