English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

In VB.NET, how can I restrict the characters of a text box to numbers and control buttons (i.e Delete, backspace...) only?

2006-10-09 05:53:17 · 4 answers · asked by Anonymous in Computers & Internet Programming & Design

In other words, only 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, backspace and delete should be allowed

2006-10-09 06:19:22 · update #1

4 answers

Use this event handler:

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim c As Char
c = e.KeyChar
If Not (Char.IsDigit(c) Or Char.IsControl(c)) Then
e.Handled = True
End If
End Sub

2006-10-09 10:34:13 · answer #1 · answered by SK 1 · 2 0

Solution 1:
========
Use a MaskedTextBox and set the "mask" property to "9999999"

Try it and check if it behaves like you want (personally I don't like it)

Solution 2
=======
Or you could use an ordinary "TextBox" with the following handler to trap the TextChanged event and detect any non digit character

Dim oldText As String

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Dim digitFound As Boolean
Dim textLength As Int16
Dim i As Int16

digitFound = True
textLength = TextBox1.Text.Length
i = 0
While (digitFound = True And i < textLength)
digitFound = Char.IsDigit(TextBox1.Text, i)
i = i + 1
End While
If digitFound = False Then
Dim caretPosition As Int16
caretPosition = TextBox1.SelectionStart
TextBox1.Text = oldText
TextBox1.SelectionStart = caretPosition - 1
Else
oldText = TextBox1.Text
End If
End Sub

2006-10-09 16:04:49 · answer #2 · answered by cd4017 4 · 1 0

Look into regular expressions. It will help you restrict whatever you want.

2006-10-09 13:16:26 · answer #3 · answered by sinkablehail1978 5 · 0 1

you need to use the masked text box

sorry i don't know what you should do for the other part

2006-10-09 12:56:59 · answer #4 · answered by Rami 5 · 0 1

fedest.com, questions and answers