1

I want to validate the users input in a textbox by not accepting anything except integers ranging from 00 to 60.

Conditions:

  1. If the user input 0 or input nothing the system should considered it as 00 (take note that I padded it with 0.
  2. I know that I can do this also in numericupdown, but for some reason I can't use that.
  3. I need to apply this in 20 textboxes.

This is the code, actually it is working. My only problem is I can't apply it to 20 textboxes, it is only working in tb_hour_1 textbox, is there something that I can do instead of indication tb_hour_1.text in this line of code Dim num As Integer = Integer.Parse(String.Format("{0}{1}", If(Tb_Hour_1.Text = String.Empty, "", Tb_Hour_1.Text), e.KeyChar.ToString())).

Code:

    Private Sub Tb_Hour_1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Tb_Minute_2.KeyPress, Tb_Minute_1.KeyPress,
    Tb_Hour_2.KeyPress, Tb_Hour_1.KeyPress

    Dim Min_Num As Integer = 0
    Dim Max_Num As Integer = 60

    If e.KeyChar <> ControlChars.Back Then
        'allow backspace for deleting
        e.Handled = Not Char.IsNumber(e.KeyChar)
        'allow numbers only
        If Not e.Handled Then
            Dim num As Integer = Integer.Parse(String.Format("{0}{1}", If(Tb_Hour_1.Text = String.Empty, "", Tb_Hour_1.Text), e.KeyChar.ToString()))
            If num < Min_Num OrElse num > Max_Num Then
                e.Handled = True
            End If
        End If
    End If
End Sub
3
  • 1
    Using a common event handler for all TextBoxes is Ok. Just replace Tb_Hour_1 by a cast, i.e. Ctype(sender,TextBox). Commented Jul 3, 2015 at 10:20
  • you have a hard coded reference to Tb_Hour_1 use sender or a NumericUpDown Commented Jul 3, 2015 at 12:17
  • @Graffito, Your comment works for me. Please answer this question so I can make it as accepted answer. Commented Jul 4, 2015 at 0:29

2 Answers 2

2

Using a common event handler for all TextBoxes is Ok. Just replace Tb_Hour_1 by a cast, i.e. :

Ctype(sender,TextBox)
Sign up to request clarification or add additional context in comments.

Comments

2

You should better create a UserControl for this purpose. which validates the input and range and instead of creating 20 textboxes, you can use your custom control then. Also, MaskedTextBox control can also be used to avoid checking length of text and it can only allow digits as well.

Also, a shortcut could be to list down all the remaining control's event like this:

Private Sub Tb_Hour_1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Tb_Minute_2.KeyPress, Tb_Minute_1.KeyPress,
    Tb_Hour_2.KeyPress, Tb_Hour_1.KeyPress, ....... further control events

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.