Solved

Numeric TextBox

Posted on 2004-08-29
8
1,379 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
 

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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

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.
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

708 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now