This is some of jmcilhinney's work that I found elsewhere. I would like to apply this to several text boxes on a form.
This link talks about that process but uses slightly different code that I have been advised to avoid. Force only number entering in textboxes-VBForums
Ok.. the code example below specifically refers to textbox name. So my question is :
How can this code be modified so that it could be used in the method of applying the code to multiple textboxes as spoken about in the posted link above.
Of course I could do it manually on each textbox but I would like to avoid that and end up with code that I can then use throughout my app as the need arises. I have modified it slightly already to fit my use..but only the textbox name and length of accepted values.
This link talks about that process but uses slightly different code that I have been advised to avoid. Force only number entering in textboxes-VBForums
Ok.. the code example below specifically refers to textbox name. So my question is :
How can this code be modified so that it could be used in the method of applying the code to multiple textboxes as spoken about in the posted link above.
Of course I could do it manually on each textbox but I would like to avoid that and end up with code that I can then use throughout my app as the need arises. I have modified it slightly already to fit my use..but only the textbox name and length of accepted values.
VB.NET:
Private Sub TextBox16_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox16.KeyPress
' Prevent non numeric characters from being entered in textbox
Dim keyChar = e.KeyChar
If Char.IsControl(keyChar) Then
'Allow all control characters.
ElseIf Char.IsDigit(keyChar) OrElse keyChar = "."c Then
Dim text = Me.TextBox16.Text
Dim selectionStart = Me.TextBox16.SelectionStart
Dim selectionLength = Me.TextBox16.SelectionLength
text = text.Substring(0, selectionStart) & keyChar & text.Substring(selectionStart + selectionLength)
If Integer.TryParse(text, New Integer) AndAlso text.Length > 4 Then
'Reject an integer that is longer than 16 digits.
e.Handled = True
ElseIf Double.TryParse(text, New Double) AndAlso text.IndexOf("."c) < text.Length - 4 Then
'Reject a real number with two many decimal places.
e.Handled = True
End If
Else
'Reject all other characters.
e.Handled = True
End If
End Sub