VB2005 question - numeric only textbox input

  • Thread starter Thread starter viv
  • Start date Start date
V

viv

how do you trap keyboard codes for text box in VB2005 ?
I'm looking for a code snippet to only allow numeric input in a text box
(same as Key event in VB6, then use Keyascii to decide action)

can anyone provide a snippet of code please

many thanks
 
Dan,

You might want to use a MaskedTextbox control.

Or you could handle a textbox's KeyDown or KeyPress events.

Or, my personal preference, you could handle the textbox's Validating event.

Kerry Moorman
 
here is my code for numeric textbox

Public Class NumTest
Inherits TextBox

Private Sub NumTest_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
If IsNumeric(e.KeyChar) And Not e.KeyChar = "-" Then
If Not IsNumeric(Me.Text & e.KeyChar) Then
e.Handled = True
Exit Sub
End If
ElseIf e.KeyChar = "." Then
If Me.Text.IndexOf(".") <> -1 Then
e.Handled = True
Exit Sub
End If
ElseIf e.KeyChar = "-" Then
If Me.SelectedText.Trim.Length = Me.Text.Trim.Length Then
Me.Text = "-0"
Me.SelectionStart = 1
Me.SelectionLength = 1
e.Handled = True
Else
If Me.SelectionStart <> 0 Or
Microsoft.VisualBasic.Left(Me.Text, 1) = "-" Then
e.Handled = True
End If
End If
ElseIf Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
End Sub


Private Sub NumTest_Leave(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Leave
If Me.Text.Length = 0 Then
Me.Text = "0"
End If
End Sub
End Class
 
In addition to the many fine answers you have received, you could use a
masked textbox instead of a textbox, and set the format to #. Then they
will only be able to put in numbers.

Robin S.
 
Back
Top