2012-02-01 87 views
1

我遇到的問題是檢查後,如果字段是空白的,我希望程序停止在那,現在它會繼續並檢查用戶名密碼,即使該字段爲空,打印錯誤的用戶名密碼我真的很新的這所以請原諒缺乏從功能知識在vb.net文本框多重驗證

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 
+0

這是一個網絡應用程序或桌面應用程序? ASP.Net?的WinForms? WPF? – DOK 2012-02-01 14:28:34

+0

@ user1182892:歡迎使用StackOverflow!您應該接受最能幫助您的答案(通過點擊旁邊的複選標記)。你也可以upvote任何其他幫助你的答案。 – 2012-02-01 15:13:08

回答

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之內,所以imho從Try/Catch內部返回是令人困惑的。

+0

omg就是這麼簡單:O和我把它移到外面試試catch :)謝謝 – Ketan 2012-02-01 14:37:03

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子句。如果發生意外錯誤,您需要知道錯誤的行號和堆棧軌跡。

+0

做完了謝謝。 – Ketan 2012-02-01 14:56:05