Solved

Numeric TextBox

Posted on 2004-08-29
8
1,383 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
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 

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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
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.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

773 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