user3329318 user3329318 - 3 months ago 14
Vb.net Question

How can I use the same code without having to retype it every time in different subs?

So I have a textbox that I only want to allow numbers in, I have the code to do it and it works fine. However I want to use it in a few textboxes, how can I use the same code without having to retype it in each textbox's KeyDown and KeyPress Subs?

The code I'm using in the KeyDown Subs is

If e.KeyCode = Keys.Back Then
BACKSPACE = True
Else
BACKSPACE = False
End If


and in the KeyPress subs I'm using

If BACKSPACE = False Then
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
e.Handled = True
End If
End If


I'm using this code for a few textboxes and was wondering how I can clean this up a bit. Can I? Thank you for your help and time!

Answer

You could make your own version of the TextBox control that inherits from the base TextBox and extends it with your custom code.

For example:

Public Class CleverTextBox
    Inherits TextBox

    Private BACKSPACE As Boolean = False

    Private Sub CleverTextBox_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
        If e.KeyCode = Keys.Back Then
            BACKSPACE = True
        Else
            BACKSPACE = False
        End If
    End Sub

    Private Sub CleverTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
        If BACKSPACE = False Then
            Dim allowedChars As String = "0123456789"
            If allowedChars.IndexOf(e.KeyChar) = -1 Then
                e.Handled = True
            End If
        End If
    End Sub
End Class

Then recompile your project, and you should see that the new CleverTextBox control has been added to the Toolbox panel, and you can drag and drop it on to your form.