【问题标题】:Multiple validation in vb.net textboxvb.net 文本框中的多重验证
【发布时间】:2012-02-01 14:26:10
【问题描述】:

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

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

【问题讨论】:

  • 这是网络应用还是桌面应用? ASP.NET?表格? WPF?
  • @user1182892:欢迎使用 StackOverflow!您应该接受对您帮助最大的答案(通过单击旁边的复选标记)。您还可以投票给任何其他对您有帮助的答案。

标签: vb.net validation textbox


【解决方案1】:

然后来自函数的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 内返回会令人困惑。

【讨论】:

  • 天哪,就是这么简单 :O 我把它移到外面试试 catch :) 谢谢
【解决方案2】:

将您的验证放在 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 子句。如果发生意外错误,您会想知道错误的行号和堆栈跟踪是什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多