Question How to allow multiple lengths on a textbox

vBn008

Member
Joined
Oct 27, 2010
Messages
9
Programming Experience
Beginner
Ok so I think this will be better than what I was thinking before.

How can I allow multiple lengths to a textbox.

something like

VB.NET:
if Not TextBox1.TextLength = 8 Or 11 Or 14 Or 18 Then msgbox("error")
 
Last edited:
Also I forgot, how can I do to restrict to only the characters or digits the function will calculate for example A and C are in hex format so I would like to allow only "1234567890ABCDEF" and B and D are Decimal so I want to allow only "1234567890"

Thanks again.
 
For the 2nd question:

Numeric Only:

VB.NET:
    Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _
    Handles TextBox1.KeyPress

        e.Handled = True

        If e.KeyChar Like "[0-9]" Then
            e.Handled = False
        End If

    End Sub

Numeric and ABCDEF:

VB.NET:
    Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _
        Handles TextBox1.KeyPress

        e.Handled = True

        If e.KeyChar Like "[0-9ABCDEF]" Then
            e.Handled = False
        End If

    End Sub

If you've got multiple TextBoxes you need to restrict you'd probably be better off with a function

VB.NET:
    Private Function MatchesPattern(ByVal e As KeyPressEventArgs, ByVal pattern As String) As Boolean
        Return Not e.KeyChar Like pattern
    End Function

Then you can change your keypress event to this

VB.NET:
    Private Sub TextBox3_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _
        Handles TextBox3.KeyPress

        e.Handled = True
        e.Handled = MatchesPattern(e, "[0-9]")

    End Sub
 
Perfect that worked just like I wanted with just one problem, I need it to accept the Backspace key. How can I add the backspace key to the e.KeyChar?
I also had to do

VB.NET:
e.KeyChar Like "[0-9ABCDEFabcdef]"

because it was only accepting if i'm using CapsLock.
 
Back
Top