在vb.net文本框中进行多次验证

时间:2012-02-01 14:26:10

标签: vb.net validation textbox

我遇到的问题是在检查字段是否为空之后我希望程序停止,现在它正在进行并检查用户名密码,即使该字段为空并打印错误的用户名密码。我真的很陌生,所以请原谅缺乏知识

Private Sub ButtonOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonOk.Click
    Try
        Dim con As New SqlConnection("Initial Catalog=stock;Data source=.;integrated security=true")
        Dim ds1 As New DataSet
        Dim da1 As New SqlDataAdapter("select * from login where Name='" & Trim(txtusername.Text) & "'and password='" & Trim(txtpassword.Text) & "'", con)


        If txtpassword.Text.Length = 0 Then
            MsgBox("Password or username feild left blank")



        End If


        If da1.Fill(ds1) Then
            adminmain.Show()
            Me.Close()
        Else

            MsgBox("Invalid Password or Username")

        End If

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

End Sub

2 个答案:

答案 0 :(得分:0)

然后来自函数的Return

If txtpassword.Text.Length = 0 Then
    MsgBox("Password or username feild left blank")
    Return
End If

但是在Try/Catch之外虽然它可行(但是finally-block将在return语句之前执行)。实际上,TextBox的验证不需要在Try/Catch内部,因此从Try / Catch中返回会很困惑。

答案 1 :(得分:0)

将您的验证放在Sub的顶部,并在找到错误后立即致电Exit Sub

Private Sub ButtonOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonOk.Click
    If txtpassword.Text.Length = 0 Then
        MsgBox("Password or username feild left blank")
        Exit Sub
    End If
    'Other validations here
    'Code to save changes here
End Sub

此外,您应该删除Try..Catch子句。如果发生意外错误,您将想知道错误的行号和堆栈跟踪。