Validación múltiple en el cuadro de texto de vb.net

The problem i am having is after checking if the field is blank i want program to stop at that, right now it is going ahead and checking the username password also even though the field is blank and printing wrong username password. i am really new at this so please excuse the lack of knowledge

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

preguntado el 01 de febrero de 12 a las 14:02

Is this a web app or a desktop app? ASP.Net? WinForms? WPF? -

@user1182892: Welcome on StackOverflow! You should accept the answer which helped you the most (by clicking on the checkmark next to it). You can also upvote any other answer which helped you. -

2 Respuestas

Entonces Regreso de la función.

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

But outside of the Try/Catch although it would work(a finally-block would be executed before the return statement). Actually the validation of the TextBox does not need to be inside of the Try/Catch, so imho it's confusing to return from within a Try/Catch.

Respondido 01 Feb 12, 18:02

omg it was that simple :O and i moved it outside try catch :) thank you - Ketan

Put your validations at the top of the Sub, and call Exit Sub as soon as an error is found.

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

Also, you should remove that Try..Catch clause. If an unexpected error occurs you'll want to know what is the line number and stack trace of the error.

Respondido 01 Feb 12, 18:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.