Reputation: 1598
Im trying to find a beginner friendly yet effective way to refrences textboxes in a vb form as an array and then loop over them checking for different conditions. Instead of having to go
If IsNumeric(firstNameTxt.Text) Then
MessageBox("First name can only contain letters")
End If
if IsNumeric(lastNameTxt.Text)
:
:
Im trying to do form validation and want to loop over all textboxes in my form checking that they only contain letter
Upvotes: 0
Views: 215
Reputation: 5545
You could just prevent them from even inputting a number which will prevent having to validate it in the first place. I have done this many times with numbers and dates but it should be as simple as this for what you want:
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
NonNumericTextboxKeyPress(sender, e)
End Sub
Public Sub NonNumericTextboxKeyPress(ByVal txt As TextBox, ByVal e As System.Windows.Forms.KeyPressEventArgs, Optional ByVal AllowNegative As Boolean = True, Optional ByVal AllowDecimal As Boolean = True)
If "1234567890".Contains(e.KeyChar) Then
e.Handled = True
End If
End Sub
Upvotes: 0
Reputation: 1326
To do form validation all textboxes
in the form checking that they only contain letter, you can use the following code:
Dim ctrl As Control
For Each ctrl In Me.Controls
If TypeOf ctrl Is TextBox And IsNumeric(ctrl.Text) Then
MsgBox(ctrl.Name.ToString & " First name can only contain letters")
End If
Next
Upvotes: 0