登录控件如果未找到用户名,则标签文本应回答未找到的用户名

时间:2011-09-28 04:47:54

标签: asp.net connection

在这里得到了一些问题。众所周知,我已经创建了一个类,其中ill只是在我的.aspx页面上实例化它。在我的.aspx页面上有一个名为login1的logincontrol。现在我在user.UserName = Nothing时收到错误,并在user.UserName = Nothing Object reference not set to an instance of an object.上停止。你能帮我调试一下这个问题。我想要的是,如果用户名不在数据库上,lblmessage应该说错误用户名无效,如果它是正确的,那么它将检查密码。请帮忙。谢谢,更多的力量。

Aspx页面

    Protected Sub LoginButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim user As New User
    Dim userDAL As New UserDAL
    user = userDAL.SelectByUsername(Login1.UserName)
    If user.UserName = Nothing Then
        Login1.FailureText = "Invalid Username"
    Else
        If Login1.Password <> user.Password Then
            Login1.FailureText = "Invalid password"
        Else
            Login1.FailureText = "success"
        End If
    End If

End Sub

UserDAL.vb

 Public Function SelectByUsername(ByVal userName As String) As User
    Try
        'select * from User where Username = 'userName'
        Dim sqlConn As New SqlConnection(_connString)
        sqlConn.Open()

        Dim sqlCmd As New SqlCommand("select * from [Users] where Username = '" & userName & "'", sqlConn)

        Dim dr As SqlDataReader = sqlCmd.ExecuteReader()

        'Create user collection
        Dim user As User = Nothing

        While dr.Read()
            'Create User object
            user = New User
            user.UserName = dr("UserName").ToString
            user.Password = dr("Password").ToString
            user.FirstName = dr("FirstName").ToString
            user.Surname = dr("Surname").ToString

        End While
        dr.Close()

        Return user
    Finally
        If _sqlConn IsNot Nothing Then
            If _sqlConn.State = Data.ConnectionState.Open Then
                _sqlConn.Close()
            End If
        End If
    End Try
    Return Nothing
End Function

2 个答案:

答案 0 :(得分:1)

首先只与user.Username进行比较,而不是与user进行比较,

If user Is Nothing Then 

如果用户名无效,为什么您的SelectByUsername函数中的Bcoz会返回Nothing。试试并回复。

答案 1 :(得分:0)

我会对此提出最简单的答案。向控件添加验证摘要,返回所需的值(“用户名无效”),然后在代码中验证执行

if(Page.IsValid) (This is C# code but VB should be very close to this)

这应该可以解决你的问题。

这是一个快速摘录

       <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
       <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="User Name Not Valid" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>

现在请注意,此错误消息将显示在文本框的右侧,但您可以设置样式,甚至将其设置为验证组。

带有验证摘要的必需字段验证程序或验证组强制客户端验证ASP.NET以进行回发,因此当提交按钮触发时,它将运行测试并确定Page.IsValid == true或false;

http://msdn.microsoft.com/en-us/library/aa479013.aspx