0

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Marilee
  • 1,598
  • 4
  • 22
  • 52
  • could you please explain little more, what you actually looking for? – Suji Sep 19 '14 at 13:32
  • 2
    `Dim textBoxes As TextBox() = { firstNameTxt, lastNameTxt, ... }` But why? It's more readable to use an `If Else`, all the more because you have different validation texts. – Tim Schmelter Sep 19 '14 at 13:33
  • @Tim thanks! Can I then reference TextBox array as such: if isNumeric(Textbox(x)) ? – Marilee Sep 19 '14 at 13:35
  • You can loop over all textboxes in the form using @TimSchmelter 's answer here: http://stackoverflow.com/questions/4673950/loop-over-all-textboxes-in-a-form-including-those-inside-a-groupbox – Matt Wilko Sep 19 '14 at 13:44
  • @Marilee: yes, with LINQ you can even check if all textboxes are numeric: `Dim allNumeric=textBoxes.All(Function(txt) IsNumeric(txt.Text))` – Tim Schmelter Sep 19 '14 at 13:50

2 Answers2

0

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
Suji
  • 1,326
  • 1
  • 12
  • 27
0

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
Steve
  • 5,585
  • 2
  • 18
  • 32