Solved

Numeric TextBox

Posted on 2004-08-29
8
1,384 Views
Last Modified: 2012-05-05
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.
 
0
Comment
Question by:Ghanisen
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 35

Expert Comment

by:YZlat
ID: 11926319
why don't you use similar function in javascript?
And then add it to your textbox:  myTextBox.Attributes.Add("onkeypress", "javascript:MyFunction()")
0
 
LVL 1

Expert Comment

by:MADeon
ID: 11926509
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
 
LVL 37

Accepted Solution

by:
gregoryyoung earned 500 total points
ID: 11926628
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
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:Ghanisen
ID: 11926665
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
 

Author Comment

by:Ghanisen
ID: 11926793
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
 
LVL 35

Expert Comment

by:YZlat
ID: 11927479
<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
 
LVL 35

Expert Comment

by:YZlat
ID: 11927484
then call it from your web form:

TextBox1.Attributes.Add("onkeypress", "javascript:NumericOnly(this.value)")
0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 11929568
           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

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Exit the loop 4 49
Error handling in asp.net site 5 34
VB.NET - Error - Object not set in Module 4 41
VB.Net Tranfer data between to VB.Net apps 8 40
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question