Solved

Numeric TextBox

Posted on 2004-08-29
8
1,381 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

895 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

14 Experts available now in Live!

Get 1:1 Help Now