Numeric TextBox

Hi,

I have a TextBox (txtSVID) which I want to accept only numeric input but without decimals (integers only).

In case the input is not an integer, I want the user to be notified, the TextBox to be emptied and the focus to remain on the TextBox until the input is an integer.

I use the following code:

Private Sub txtSVID_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSVID.KeyPress
        Dim flag As Boolean
        Dim KeyAscii As Integer
        KeyAscii = Asc(e.KeyChar)

        If flag = False Then
            ' Set the flag to True to prevent re-entry of the code below.
            flag = True
            ' Determine if the text of the control is a number.
            Select Case KeyAscii
                Case 48 To 57
                Case Else
                    'provide no handling for any other keys
                    KeyAscii = 0
                    MsgBox("You must enter a positive integer")
            End Select
            ' Reset the flag so other TextChanged events are processed correctly.
            flag = False
            Exit Sub
        End If
    End Sub

It does prompt the user each time he tries to enter an invalid character but the TextBox content is not cleared from the invalid characters and the user may leave the TextBox leaving invalid characters in the TextBox.

I would also appreciate if I could format the TextBox text with thousands separators.

Any help would be greatly appreciated.
 
GhanisenAsked:
Who is Participating?
 
gregoryyoungConnect With a Mentor Commented:
I believe you will find this more acceptable

Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.TextBox1 = New System.Windows.Forms.TextBox
        Me.SuspendLayout()
        '
        'TextBox1
        '
        Me.TextBox1.Location = New System.Drawing.Point(88, 64)
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.TabIndex = 0
        Me.TextBox1.Text = ""
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 273)
        Me.Controls.Add(Me.TextBox1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        'gets fired on copy/paste
        If Me.TextBox1.Text <> "" AndAlso Not IsNumeric(Me.TextBox1.Text) Then
            Me.TextBox1.Text = ""
            MsgBox("You must enter a positive integer")
        End If
    End Sub

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        Dim KeyAscii As Integer
        KeyAscii = Asc(e.KeyChar)

        Select Case True
            Case Char.IsDigit(e.KeyChar)
            Case Char.IsControl(e.KeyChar)
            Case Else
                e.Handled = True
                MsgBox("You must enter a positive integer")
        End Select
    End Sub
End Class


you can also inherit from the textbox control to create a "numerictextbox" control ... if you want to learn how to do this let me know.

Cheers,

Greg
0
 
YZlatCommented:
why don't you use similar function in javascript?
And then add it to your textbox:  myTextBox.Attributes.Add("onkeypress", "javascript:MyFunction()")
0
 
MADeonCommented:
It's in a slightly different direction from what you've taken, but a possible solution would be to use the NumericUpDown control. It allows you to specify the number of decimal places to allow (including zero) and whether to display a thousands separator. If the user tries to enter an invalid character, it prevents them from doing so and just beeps.

Just to be safe, you'll probably also want to include code to handle the Validating event of the NumericUpDown, since the control does not prevent the user from pasting non-numeric data.
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
GhanisenAuthor Commented:
Hi,

To YZlat : I don't see how I can use the Java function. You don't even give the function's code. I'm not at all familiar with Java Script.

To MADeon: The numericUpDown control works fine but it has the Updown I don't like. Do you know how to get rid of it if that is at all feasible (I doubt it).

Meanwhile I found this code which makes the textbox ignore all non-numeric characters:
 
Private Sub txtSVID_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSVID.KeyPress
        'Limiter la saisie à des caractères numériques
        If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub

So if you find how to format the texbox with thousands separators or how to get rid of the >UpDown in the NumericUpDown control you'll get the 500 hundreds points.

Thanks to both of you for your prompt response.
 
0
 
GhanisenAuthor Commented:
Hi,

To Gregoryyoung: Thanks you solution is Ok for the numeric entry. I did not have the part dealing with the cut and paste.

Do you have a solution for formatting the textbox with thousand separators?

Thanks
0
 
YZlatCommented:
<script language="javascript">
<!--
function NumericOnly(myText)
{
   var str = "":
   var strNumber = "1234567890";
   for(i=0;i<myText.length;i++) if(strNumber.indexOf(myText.charAt(i))>=0) str+=myText.charAt(i);
   return str;
}


//-->
</script>
0
 
YZlatCommented:
then call it from your web form:

TextBox1.Attributes.Add("onkeypress", "javascript:NumericOnly(this.value)")
0
 
gregoryyoungCommented:
           Me.TextBox1.Text = Format(Double.Parse(Me.TextBox1.Text), "##,##0") will format it with thousand seperators. you can put this in the text changed event but if you do you will need to handle moving the location of the string where the cursor is the following example does this.

Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.TextBox1 = New System.Windows.Forms.TextBox
        Me.SuspendLayout()
        '
        'TextBox1
        '
        Me.TextBox1.Location = New System.Drawing.Point(88, 64)
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.TabIndex = 0
        Me.TextBox1.Text = ""
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 273)
        Me.Controls.Add(Me.TextBox1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        'gets fired on copy/paste
        If Me.TextBox1.Text <> "" AndAlso Not IsNumeric(Me.TextBox1.Text) Then
            Me.TextBox1.Text = ""
            MsgBox("You must enter a positive integer")
        Else
            Me.TextBox1.Text = Format(Double.Parse(Me.TextBox1.Text), "##,##0")
            Me.TextBox1.SelectionStart = Me.TextBox1.Text.Length
        End If
    End Sub

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        Dim KeyAscii As Integer
        KeyAscii = Asc(e.KeyChar)

        Select Case True
            Case Char.IsDigit(e.KeyChar)
            Case Char.IsControl(e.KeyChar)
            Case Else
                e.Handled = True
                MsgBox("You must enter a positive integer")
        End Select
    End Sub
End Class
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.