Simple question about VB.Nnet windows form validation

SteveOOOsw

n00b
Joined
Dec 3, 2005
Messages
19
How would one verify that data is entered into a textbox and if not the method is aborted?

Here is what I am having problems with...

The following will display the error message but not abort the method
Code:
If (UserNameTextBox.Text.Length = 0) Then
            MessageBox.Show("User name is required.")
Else
            strUserName = UserNameTextBox.Text
End If

Or throwing a custom exception will display the error message and abort the method but it will also display an unhanded exception message
Code:
If (UserNameTextBox.Text.Length = 0) Then
            Throw New RequiredFieldException("User name is required.")
Else
            strUserName = UserNameTextBox.Text
End If
 
I hate VB, so I never use it. Though I do have *some* experience.

In your situation I would just do the following:
Code:
Private Sub Test()
If (UserNameTextBox.Text.Length = 0) Then
            MessageBox.Show("User name is required.")
            GoTo Quit
Else
            strUserName = UserNameTextBox.Text
End If

' do other stuff / checks / etc

' more code la la la

Quit:
End Sub

Pretty simple fix, but I think that's what you're wanting?

Hope it helps.
 
that works, but is there a cleaner way? Also, a way to display multiple messages if two input fields are left blank?

Code:
        If (UserNameTextBox.Text.Length = 0) Then
            MessageBox.Show("User name is required.")
            UserNameTextBox.Focus()
            GoTo Quit
        Else
            strUserName = UserNameTextBox.Text
        End If

        If (PasswordTextBox.Text.Length = 0) Then
            MessageBox.Show("Password is required.")
            PasswordTextBox.Focus()
            GoTo Quit
        Else
            strPassword = PasswordTextBox.Text
        End If
Quit:
 
Never use GoTo.

Never.

Use Return in .Net. In VB6 use Exit Sub or Exit Function.

Code:
Dim errcond as boolean = false
If txtusername.text.trim = "" Then
  Messagebox.show("...")
  errcond = true
End If
If txtpassword.text.trim = "" Then
  Messagebox.show("...")
  errcond = true
End If

If errcond Then Return
 
Back
Top