I am desiging a Form in which I am asking user to enter:
Name in Textbox1
ID Card Number in Text2

here i want to code for textbox2 that it accepts only numbers and "-" but don't know how to control. Can anyone help me?

Recommended Answers

All 18 Replies

The following code will allow/prevent the entry of specific keys. Add a Case statement for each key or range of keys you want to allow. Note that you have to add a Case to allow BackSpace but not Left/Right Arrow or Delete.

Public Class Form1

    Private Sub TextBox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

        'Remove the following line for production code
        Me.Text = "ASC " & Asc(e.KeyChar) & "    HEX " & Asc(e.KeyChar).ToString("X2")

        Select Case e.KeyChar
            Case "0" To "9"     'digit
            Case "-"            'dash
            Case Chr(8)         'backspace
            Case Else:          e.Handled = True
        End Select

    End Sub

End Class

The following codes prevent the keys other than Digits and '-'. And you can press the deletion and nevigation keys.

Public Class Form1

    Private Sub Form1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If TypeOf Me.ActiveControl Is TextBox Then
            If Not ((e.KeyCode = Keys.D0) Or (e.KeyCode = Keys.D1) Or (e.KeyCode = Keys.D2) Or (e.KeyCode = Keys.D3) Or (e.KeyCode = Keys.D4) Or (e.KeyCode = Keys.D5) Or (e.KeyCode = Keys.D6) Or (e.KeyCode = Keys.D7) Or _
                    (e.KeyCode = Keys.D8) Or (e.KeyCode = Keys.D9) Or (e.KeyCode = Keys.NumPad0) Or (e.KeyCode = Keys.NumPad1) Or (e.KeyCode = Keys.NumPad2) Or (e.KeyCode = Keys.NumPad3) Or (e.KeyCode = Keys.NumPad4) Or (e.KeyCode = Keys.NumPad5) Or _
                    (e.KeyCode = Keys.NumPad6) Or (e.KeyCode = Keys.NumPad7) Or (e.KeyCode = Keys.NumPad8) Or (e.KeyCode = Keys.NumPad9) Or (e.KeyCode = Keys.OemMinus) Or (e.KeyCode = Keys.Subtract) Or (e.KeyCode = Keys.NumLock) Or _
                    (e.KeyCode = Keys.Back) Or (e.KeyCode = Keys.Delete) Or (e.KeyCode = Keys.Home) Or (e.KeyCode = Keys.End) Or (e.KeyCode = Keys.Left) Or (e.KeyCode = Keys.Right)) Then
                e.SuppressKeyPress = True
            End If
        End If
    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        TextBox1.Text = ""

    End Sub

End Class
commented: There are several good ways to implement key filtering. This isn't one of them. -3

I find this method really useful. AllowedCodes also holds values for Delete, BackSpace, Home, End, Numeric Keypad Numbers, Standard Numbers etc.

    Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown


        If Not (KeyAllowed(e.KeyCode)) Then e.SuppressKeyPress = True

    End Sub

    Private Function KeyAllowed(Key As System.Windows.Forms.Keys) As Boolean

        Console.WriteLine(Key)

        Dim AllowedCodes() As Byte = {35, 36, 46, 37, 38, 39, 40, 8, 189 _
                                     , 45, 48, 48, 50, 51, 52, 53, 54, 55, 56, 57 _
                                     , 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 109}

        If AllowedCodes.Contains(CInt(Key)) Then
            Return True
        Else
            Return False
        End If

    End Function

I find this way you can ammend your allowed list with the greatest of ease.

Most textbox filters are for categories of keystrokes - for example, upper and/or lower case letters, digits, etc. In these cases it is faster (although not noticibly) and clearer (which is almost always desirable) to use ranges. As such,

Select Case e.KeyChar
    Case "0" To "9"     'allow digit
    Case "a" To "z"     'allow lower case letter
    case 'A' To 'Z'     'allow upper case letter
    Case Else:          e.Handled = True
End Select

is immediately obvious even without the comments. It is also easy to modify. If you use a list (or array) of numbers like you are doing, it is necessary to first translate the numbers into the corresponding characters, then scan through that list to ensure that the coder did not (deliberately or accidentally) omit one character, or incorrectly enter a value. That is not good coding.

I'm sorry Reverend Jim... I find the reasnoble alternative solution I provided quite acceptable and much more versatile. Not good coding? I'm sorry sweet heart, did I venture away from your solution. Find a bug in my solution and I'll reconsider the fact you aren't just power tripping. A down vote for an alternative... grow up.

I do not understand that , why I try to make busy a Textbox to check and filter the key stroke every time when I strike the keys. At the time of searching a large database on every stroke, on which work a TextBox concentrate , “To search a Database” or “Filtering inputs”? Why we try to divert it. Why couldn’t use a FormLevel Fiteration to concentrate it on its main work?

Havent you watch last tutorial:
Reverend Jim code is true too
but i use simple coding
No Problem: CHECK THIS CODE:

TEXTBOX > KEYPRESS EVENT

If Asc(e.KeyChar) <> 8 Then
    If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
        e.Handled = True
    End If
End If

6812e8f1880408b7688a497a9b5bae7a

It would also be important prevent a user from Pasting as all these solutions would be rendered useless

TextBox1.ShortcutsEnabled=False

AGREE....
All the stuff will useless if Shortcuts are enable...
but you can also verify if you have enable shortcut key.
wanna see how?>?

go to textbox_LEAVE event
example

Private Sub TextBox_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.Leave
  If Not IsNumeric(TextBox2.Text) Then
    MsgBox("please enter only ID")
    TextBox2.Text = ""
  Else : ' do nothing
  End If
End Sub

so if the textbox contain any other than integer it will msg and clear text.
:p

That's not quite there as a solution Deep Modi, for example IsNumeric(1234-5678-91011) [depending on the ID format] would return false. Also clearing a user input isn't cool beans. It could get increddibly frustrating having to re-type the whole ID each time there was a mistake.

I'm sorry sweet heart, did I venture away from your solution. Find a bug in my solution and I'll reconsider the fact you aren't just power tripping. A down vote for an alternative... grow up.

It's one thing to express an opinion. My opinion was that clear, concise code is generally better than code that is less clear. You have a different opinion. That is perfectly valid. Note, however, that I gave reasons why I believe one form is better coding whereas you chose to resort to sarcasm and put-downs. I'll leave it up to others to decide which of us needs to develop a little maturity.

@Deep this is most frustrating to a user to get a message at the time of leaving the TextBox. If you want to input a 10 to 15 charecters, at the time of leaving, you get a wrong message, it could be more frustrating to you. You can use any of the KeyPress or keyDown event, but KeyDown event if more convenient.

@Santanu Das & @J.C. SolvoTerra
HAHAHA, Correct but havent you read the code that I said before it, (about Keypress)
How can he be mistake if he dont copy...
The user will not able to enter any of others characters

and if he paste the coding then only textbox will contains other than of numeric.

this is most trating to a user to get a message at the time of leaving the TextBox. If you want to input a 10 to 15 char

he time of leaving, you get a wrong message, it could be more frustrating to you. You

his is most frustrating to a user to get a message at the time of leaving the TextBox. If you want to input a 10 to 15 charecters, at the time of leaving, you get a wrong message

The leave event is used as to sure that the user haveing the textbox with all Numeric (intergers) only.

And I am just giving example.
Programmer can make the baqckground RED.
and make the submit btn disable too...

There are hundreds of way to get somethings related to this and to save more time.

Have you ever seen this type of format except to input ther serial for any program.?

IsNumeric(1234-5678-91011) [depending on the ID format] would return false

I dont think so.
And if this is the format Programmer should change rightclick menu (Disable Paste btn) and only need to enter the KEYPRESS EVENT.

I need to apologise to Reverand Jim for my prior outburst, and indeed to the other participants on this thread. It was rude and uncalled for.

@Deep Modi. None of us know the format but aligulsoomro asked for the method to include the use of "-". We cant assume the ID is not 2234-5678... but assume it will be -12345678.

commented: No problem. +12

@Deep Modi, As per posting of AliGulSoomro1, he wants to input only the 'Digits' and '-', but not the chars. So, there is no question to give any chance to input a char.
This is the cause to restrict the chars at the time of inputting, not checking at the time of leaving. It is true that a programmer has various process to flag up for wrong input. Sometimes, a user couldn't understand what wrong he has done. I thought, presntly no one use a Red background for wrong. And for Submit Button, it would be disabled to that time whenever the text box achieved the text length as desired. Not only good codification, but designing also be a part of good programming.

@J.C. Solvo Terra, You are right and I appriciate you that AliGulSoomro1 never says about the format of inputting i.e. where the position of '-' would be.
We can try to restrict the '-' sign to put at first

    Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown

        if (Trim(TextBox1.Text) = "") Then
           If (e.KeyCode = Keys.Subtract) Then e.SuppressKeyPress = True 
        EndIf

        If Not (KeyAllowed(e.KeyCode)) Then e.SuppressKeyPress = True

    End Sub

I think this thread needs flagging as solved... like 18 posts ago

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.