How to restrict TextBox?

mmb

Active member
Joined
Aug 1, 2004
Messages
42
Programming Experience
1-3
I want my textbox to take only letters as Input, no numbers or other keys.

And Viceversa that I want Only numbers as Input ,no letters or other keys.

PLS HELP ME.
 
And if you need this functionality in other projects or more than once in a project, I would strongly suggest you modify the code JuggaloBrotha will be posting and make a user control.
 
lucky fer y'all it's jes a simple sub...

VB.NET:
'In the form code
Private Sub textbox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles textbox1.KeyPress
        Call MyKeyPress(sender, e, strValidChars)
    End Sub

'In a module
Public Const strValidChars As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

Public Sub MyKeyPress(ByRef Sender As Object, ByRef e As System.Windows.Forms.KeyPressEventArgs, ByVal ValidChars As String)
        Dim TextBox As TextBox
        Dim strLastChar As String
        TextBox = CType(Sender, TextBox)
        If Asc(e.KeyChar) <> Keys.Back Then
            If InStr(ValidChars, e.KeyChar) = 0 Then
                e.Handled = True
            Else
                If e.KeyChar.IsLetter(e.KeyChar) = True Then
                    TextBox.SelectedText = ""
                    If Not TextBox.TextLength = 0 Then
                        strLastChar = Mid(TextBox.Text, TextBox.TextLength, 1)
                    Else
                        strLastChar = "'"
                    End If
                    If strLastChar = " " Or strLastChar = "-" Or strLastChar = "'" Then
                        TextBox.SelectedText = e.KeyChar.ToUpper(e.KeyChar)
                        e.Handled = True
                    End If
                End If
            End If
        End If
    End Sub

this actually caplitalizes the first character entered, i initially made it for like a first name/last name textbox for database entries but you can tweak it however ya need ta get what ya want now that you've got the base code/base logic
 
Last edited:
VB.NET:
'in the keypress event of the textbox
'it only accept numbers.
 If Char.IsDigit(e.KeyChar) Or e.KeyChar = "." Or Char.IsControl(e.KeyChar) Or e.KeyChar = "-" Then
            e.Handled = False
        Else
            e.Handled = True
        End If
 
because the masked textbox isnt in the .netframework 1.1 (and lower) vb2005 uses .netframework v2 so yea, we use keypress for now (or write your own masked edit box)
 
Back
Top