Looking for a better way to evaluate textbox controls
I have multiple textboxes that should have numeric values and others that need to have some kind of entry added. So far I have been doing it this way but I am wondering if there is a better way. How would you do this?
VB Code:
Dim strAction As String = txtAction.Text
Select Case strAction
Case "A"
If IsNumeric(txtEmp.Text) = False Then
MsgBox("Employee number must be a numeric value.", _
MsgBoxStyle.OKOnly, "Employee Number Error")
txtEmp.Focus()
Exit Sub
End If
If IsNumeric(txtDayCode.Text) = False Then
MsgBox("This field must be a numeric value 1-7.", _
MsgBoxStyle.OKOnly, "Day Code Error")
txtDayCode.Focus()
Exit Sub
End If
If (txtJobNumber.Text) = "" Then
MsgBox("The job number field can not be left blank.")
txtJobNumber.Focus()
Exit Sub
End If
If (txtPC.Text) = "" Then
MsgBox("The Pc Field can not be left blank.")
txtPC.Focus()
Exit Sub
End If
If (txtTime.Text) = "" Then
MsgBox("The time field can not be left blank.")
txtTime.Focus()
Exit Sub
End If
If (txtAmount.Text) = "" Then
MsgBox("The amount field can not be left blank.")
txtAmount.Focus()
Exit Sub
End If
Re: Looking for a better way to evaluate textbox controls
You could try adding the type of validation to the tag property and then just loop through the textboxes on the form ie
For those that must be numeric add numeric to the tag property and those that can not be blank add noNull to the tag property then just loop through like so
VB Code:
For Each ctl As Control In Me.Controls
If TypeOf ctl Is TextBox Then
Dim tBox As TextBox = DirectCast(ctl, TextBox)
Select Case tBox.Tag
Case "numeric"
Dim intTest As Integer
If Not Integer.TryParse(tBox.Text, intTest) Then
MessageBox.Show(tBox.Name & " must be numeric")
tBox.Focus()
End If
Case "noNull"
If tBox.Text = String.Empty Then
MessageBox.Show(tBox.Name & " can not be null")
tBox.Focus()
End If
End Select
End If
Next
or another example is if you want custom error messages, put the error message in the tag property but start the line with an identifier for type like so
txtEmp.Tag = "N*Employee number must be a numeric value."
txtJobNumber.Tag = "R*"The job number field can not be left blank."
where N* signifies a numeric field and R* signifies required (just examples, you could use whatever you want)
VB Code:
For Each ctl As Control In Me.Controls
If TypeOf ctl Is TextBox Then
Dim tBox As TextBox = DirectCast(ctl, TextBox)
Dim type As String = tBox.Tag.ToString.Substring(0, 2)
Select Case type
Case "N*"
Dim intTest As Integer
If Not Integer.TryParse(tBox.Text, intTest) Then
MessageBox.Show(tBox.Tag.ToString.Replace(type, String.Empty))
tBox.Focus()
End If
Case "R*"
If tBox.Text = String.Empty Then
MessageBox.Show(tBox.Tag.ToString.Replace(type, String.Empty))
tBox.Focus()
End If
End Select
End If
Next