Results 1 to 11 of 11

Thread: How do i set a textbox to accept only numbers?

  1. #1

    Thread Starter
    Lively Member
    Join Date
    May 2003
    Posts
    98

    How do i set a textbox to accept only numbers?

    can anyone help?

  2. #2
    Addicted Member rdove's Avatar
    Join Date
    Dec 2002
    Location
    Indianapolis
    Posts
    251
    Ok there are a couple of ways you can do this, I need to find out which way you are wanting to go about this.

    1. You can validate that only numbers have been entered into the text box upon a button, label, etc... action

    Code:
    if isnumeric(textbox1.text) = true then
    
      'do something
    
    else
    
      msgbox "Please enter numbers only"
      textbox1.focus
      exit sub
    
    end if
    or

    2. You can validate while the users is typing in the text box.

    You can use the is_changed (i think) event of the textbox and find set it to accept certain keys only

    something like:

    Code:
    if not keys.ascii = numeric1 then
      msgbox "Please enter numbers only"
      textbox1.focus
      exit sub
    end if
    I don't have VB in front on this computer so I don't know who accurate the syntax is, but I hope it is good enough for you to get the idea.
    ~Ryan





    Have I helped you? Please Rate my posts.

  3. #3
    Sleep mode
    Join Date
    Aug 2002
    Location
    RUH
    Posts
    8,083
    Ideal event for that is Keypress event . Here you go :
    VB Code:
    1. Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    2.         Dim KeyAscii As Integer
    3.         KeyAscii = Asc(e.KeyChar)
    4.  
    5.         Select Case KeyAscii
    6.             Case Asc("0") To Asc("9")
    7.                 'acceptable keystrokes
    8.                 e.Handled = False
    9.             Case Else
    10.                 e.Handled = True
    11.         End Select
    12.     End Sub

  4. #4

    Thread Starter
    Lively Member
    Join Date
    May 2003
    Posts
    98
    Hmmm, i worded it a bit wrong, i actually want to take all the text and leave just the numbers

  5. #5
    l33t! MrPolite's Avatar
    Join Date
    Sep 2001
    Posts
    4,428
    I made my own textbox a while ago and it works perfectly for me... I don't feel like explaining it now though... see if you can figure it out:

    VB Code:
    1. Imports System.ComponentModel
    2.  
    3.     Public Class NumericTextBox
    4.         Inherits Windows.Forms.TextBox
    5.  
    6.         Public Event InvalidKeyEntered(ByVal sender As NumericTextBox)
    7.         Public Event InvalidTextEntered(ByVal sender As NumericTextBox)
    8.         Public Event ValueOutOfRange(ByVal sender As NumericTextBox)
    9.         Public Event ValueChanged(ByVal sender As NumericTextBox)
    10.         Public Event KeyPressEvent(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
    11.  
    12.  
    13.  
    14. #Region " Properties "
    15.         Private mAllowInvalidBeforeValidate As Boolean = False
    16.         <Browsable(True), _
    17.          Description("If true, accepts pasting none-numeric text in the NumericTextBox, before " & _
    18.                      "the Validate event is fired."), _
    19.          Category("Additional Setting"), _
    20.          DefaultValue(False)> _
    21.         Public Property AllowInvalidBeforeValidate() As Boolean
    22.             Get
    23.                 Return mAllowInvalidBeforeValidate
    24.             End Get
    25.             Set(ByVal Value As Boolean)
    26.                 mAllowInvalidBeforeValidate = Value
    27.             End Set
    28.         End Property
    29.  
    30.  
    31.         Private mAutoFormat As Boolean = True
    32.         <Browsable(True), _
    33.          Description("If true, will format the entered value after the TextBox is validated. " & _
    34.                       "Any extra zeros after floating point will be removed."), _
    35.          Category("Additional Setting"), _
    36.          DefaultValue(True)> _
    37.         Public Property AutoFormat() As Boolean
    38.             Get
    39.                 Return mAutoFormat
    40.             End Get
    41.             Set(ByVal Value As Boolean)
    42.                 mAutoFormat = Value
    43.             End Set
    44.         End Property
    45.  
    46.  
    47.         Private mAcceptDecimal As Boolean = False
    48.         <Browsable(True), _
    49.          Description("If true, will accept decimal numbers."), _
    50.          Category("Additional Setting"), _
    51.          DefaultValue(False)> _
    52.         Public Property AcceptDecimal() As Boolean
    53.             Get
    54.                 Return mAcceptDecimal
    55.             End Get
    56.             Set(ByVal Value As Boolean)
    57.                 mAcceptDecimal = Value
    58.             End Set
    59.         End Property
    60.  
    61.  
    62.         Private mAcceptNegative As Boolean = False
    63.         <Browsable(True), _
    64.          Description("If true, will accept negative numbers."), _
    65.          Category("Additional Setting"), _
    66.          DefaultValue(False)> _
    67.         Public Property AcceptNegative() As Boolean
    68.             Get
    69.                 Return mAcceptNegative
    70.             End Get
    71.             Set(ByVal Value As Boolean)
    72.                 mAcceptNegative = Value
    73.             End Set
    74.         End Property
    75.  
    76.  
    77.         Private mMinValue As Double = Double.MinValue
    78.         <Browsable(True), _
    79.          Description("Minimum value that the NumericTextBox accepts."), _
    80.          Category("Additional Setting"), _
    81.          DefaultValue(Double.MinValue)> _
    82.          Public Property MinValue() As Double
    83.             Get
    84.                 Return mMinValue
    85.             End Get
    86.             Set(ByVal Value As Double)
    87.                 mMinValue = Value
    88.             End Set
    89.         End Property
    90.  
    91.  
    92.         Private mMaxValue As Double = Double.MaxValue
    93.         <Browsable(True), _
    94.          Description("Maximum value that the NumericTextBox accepts."), _
    95.          Category("Additional Setting"), _
    96.          DefaultValue(Double.MaxValue)> _
    97.          Public Property MaxValue() As Double
    98.             Get
    99.                 Return mMaxValue
    100.             End Get
    101.             Set(ByVal Value As Double)
    102.                 mMaxValue = Value
    103.             End Set
    104.         End Property
    105.  
    106.  
    107.         Private mOnOutOfRangeSetToLim As Boolean = True
    108.         <Browsable(True), _
    109.          Description("If the user enters a value larger than MaxValue, it will be set to" & _
    110.                      "MaxValue. If a value smaller than MinValue is entered, it will be set" & _
    111.                      " to MinValue. If False, restores the last valid value,"), _
    112.          Category("Additional Setting"), _
    113.          DefaultValue(True)> _
    114.         Public Property OnOutOfRangeSetToLim() As Boolean
    115.             Get
    116.                 Return mOnOutOfRangeSetToLim
    117.             End Get
    118.             Set(ByVal Value As Boolean)
    119.                 mOnOutOfRangeSetToLim = Value
    120.             End Set
    121.         End Property
    122. #End Region
    123.  
    124.  
    125.         Private mLastValidText As String
    126.         Private Property lastValidText() As String
    127.             Get
    128.                 If mLastValidText Is Nothing Then
    129.                     If MinValue > 0 Then
    130.                         mLastValidText = MinValue.ToString
    131.                     Else
    132.                         mLastValidText = "0"
    133.                     End If
    134.                 End If
    135.  
    136.                 Return mLastValidText
    137.             End Get
    138.             Set(ByVal Value As String)
    139.                 Value = Value.Trim
    140.                 If Value = "" Then
    141.                     Value = lastValidText
    142.                 ElseIf CLng(mLastValidText) < MinValue Then
    143.                     mLastValidText = MinValue.ToString
    144.                 ElseIf CLng(mLastValidText) > MaxValue Then
    145.                     mLastValidText = MaxValue.ToString
    146.                 Else
    147.                     mLastValidText = Value
    148.                 End If
    149.             End Set
    150.         End Property
    151.  
    152.  
    153.         Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
    154.             If Not AllowInvalidBeforeValidate Then
    155.                 checkText()
    156.                 '            LastValidText = Me.Text
    157.             End If
    158.             MyBase.OnTextChanged(e)
    159.         End Sub
    160.  
    161.  
    162.  
    163.         Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
    164.             Dim BACK_SPACE As Integer = 8
    165.             Dim ENTER As Integer = 13
    166.             Dim KeyASCII As Integer = Asc(e.KeyChar)
    167.             'Not a number
    168.             If KeyASCII <> BACK_SPACE AndAlso KeyASCII <> ENTER AndAlso _
    169.                KeyASCII < 48 OrElse KeyASCII > 57 Then
    170.                 ' Accept decimal character, and the negative sign if set to accept them
    171.                 If Not (AcceptNegative AndAlso e.KeyChar = "-"c) AndAlso _
    172.                    Not (AcceptDecimal AndAlso e.KeyChar = "."c) Then
    173.                     ' Cancel the entered key, not a valid key
    174.                     e.Handled = True
    175.                     RaiseEvent InvalidKeyEntered(Me)
    176.                 End If
    177.  
    178.             ElseIf KeyASCII = ENTER Then
    179.                 OnValidated(Nothing)
    180.                 e.Handled = True
    181.                 Me.SelectAll()
    182.             End If
    183.             'RaiseEvent KeyPressEvent(Me, e)
    184.             MyBase.OnKeyPress(e)
    185.         End Sub
    186.  
    187.  
    188.         ' Checks to see if the entered text is a number
    189.         Private Sub checkText()
    190.             Me.Text = Me.Text.Trim
    191.             If Me.Text = "" Then Exit Sub
    192.  
    193.             Try
    194.                 Dim tmp As Double = CDbl(Me.Text)
    195.             Catch
    196.                 Me.Text = lastValidText
    197.                 RaiseEvent InvalidTextEntered(Me)
    198.             End Try
    199.         End Sub
    200.  
    201.         ' Formats the entered number (has to be a number). For example, removes extra zeros
    202.         Private Sub formatText()
    203.             Try
    204.                 Dim tmp As Double = CDbl(Me.Text)
    205.                 Me.Text = tmp.ToString
    206.             Catch
    207.                 MsgBox("DEBUG: WARNING! UNEXPECTED ERROR!", MsgBoxStyle.Critical, "ERROR!!!")
    208.             End Try
    209.  
    210.         End Sub
    211.  
    212.         ' Changes to see if the entered number is in the valid range (has to be a number).
    213.         ' Valid range is from MinValue to MaxValue
    214.         Private Sub checkRange()
    215.             Try
    216.                 Dim tmp As Double = CDbl(Me.Text)
    217.                 If tmp < MinValue Then
    218.                     If mOnOutOfRangeSetToLim Then
    219.                         Me.Text = MinValue.ToString
    220.                     Else
    221.                         Me.Text = lastValidText
    222.                         RaiseEvent ValueOutOfRange(Me)
    223.                     End If
    224.                 ElseIf tmp > MaxValue Then
    225.                     If mOnOutOfRangeSetToLim Then
    226.                         Me.Text = MaxValue.ToString
    227.                     Else
    228.                         Me.Text = lastValidText
    229.                         RaiseEvent ValueOutOfRange(Me)
    230.                     End If
    231.                 End If
    232.             Catch
    233.                 MsgBox("DEBUG: WARNING! UNEXPECTED ERROR!", MsgBoxStyle.Critical, "ERROR!!!")
    234.             End Try
    235.         End Sub
    236.  
    237.         Protected Overrides Sub OnValidated(ByVal e As System.EventArgs)
    238.             checkText()
    239.             If Me.Text = "" Then
    240.                 Me.Text = lastValidText
    241.             End If
    242.             checkRange()
    243.             If AutoFormat Then formatText()
    244.  
    245.  
    246.             lastValidText = Me.Text
    247.             RaiseEvent ValueChanged(Me)
    248.  
    249.             MyBase.OnValidated(e)
    250.         End Sub
    251.  
    252.         Public Sub New()
    253.             ' Since lastValidText is not set yet, the property will generate a
    254.             ' default value. See the lastValidText property
    255.             Me.Text = mLastValidText
    256.         End Sub
    257.        
    258.     End Class
    and no need to explain I guess, that is a usercontrol
    rate my posts if they help ya!
    Extract thumbnail without reading the whole image file: (C# - VB)
    Apply texture to bitmaps: (C# - VB)
    Extended console library: (VB)
    Save JPEG with a certain quality (image compression): (C# - VB )
    VB.NET to C# conversion tips!!

  6. #6
    Frenzied Member dynamic_sysop's Avatar
    Join Date
    Jun 2003
    Location
    Ashby, Leicestershire.
    Posts
    1,142
    Code:
        Private Const GWL_STYLE As Integer = CInt(-16)
        Private Const ES_NUMBER As Integer = CInt(&H2000)
        Private txtstyle As Integer
        Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Integer, ByVal nIndex As Integer) As Integer
        Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Integer, ByVal nIndex As Integer, ByVal dwNewLong As Integer) As Integer
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            txtstyle = GetWindowLong(TextBox2.Handle.ToInt32, GWL_STYLE)
            '/// set textbox to only accept numbers.
            SetWindowLong(TextBox2.Handle.ToInt32, GWL_STYLE, txtstyle Or ES_NUMBER)
        End Sub
    
        Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
            Select Case Asc(e.KeyChar)
                Case 22
                    e.Handled = True '/// prevent pasting letters in to textbox.
                Case Else
                    e.Handled = False
            End Select
        End Sub
    
        Private Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
            If Not IsNumeric(TextBox2.Text) Then
                MessageBox.Show("Sorry only numerics allowed!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                TextBox2.Text = "" '/// make sure no letters are allowed in.
            End If
        End Sub
    hope this helps a little , it will make a textbox only accept numerics.
    ~
    if a post is resolved, please mark it as [Resolved]
    protected string get_Signature(){return Censored;}
    [vbcode][php] please use code tags when posting any code [/php][/vbcode]

  7. #7
    l33t! MrPolite's Avatar
    Join Date
    Sep 2001
    Posts
    4,428
    hmm what does the API do? sounds like you're filtering the entered keys in the KeyPress event
    rate my posts if they help ya!
    Extract thumbnail without reading the whole image file: (C# - VB)
    Apply texture to bitmaps: (C# - VB)
    Extended console library: (VB)
    Save JPEG with a certain quality (image compression): (C# - VB )
    VB.NET to C# conversion tips!!

  8. #8
    Frenzied Member dynamic_sysop's Avatar
    Join Date
    Jun 2003
    Location
    Ashby, Leicestershire.
    Posts
    1,142
    the api sets the textbox's window style to numbers only
    here's a quote from msdn library :
    ES_NUMBER
    Allows only digits to be entered into the edit control. Note that, even with this set, it is still possible to paste non-digits into the edit control.
    To change this style after the control has been created, use SetWindowLong.
    the keypress / text changed handlers are to prevent the pasting of none numeric chars.
    ~
    if a post is resolved, please mark it as [Resolved]
    protected string get_Signature(){return Censored;}
    [vbcode][php] please use code tags when posting any code [/php][/vbcode]

  9. #9
    l33t! MrPolite's Avatar
    Join Date
    Sep 2001
    Posts
    4,428
    Originally posted by dynamic_sysop
    the api sets the textbox's window style to numbers only
    here's a quote from msdn library :


    the keypress / text changed handlers are to prevent the pasting of none numeric chars.
    oooh ok so it doesnt let you enter non-numeric keys.... got it... my textbox is better it rules
    what if you have to enter a decimal or a negative number?
    rate my posts if they help ya!
    Extract thumbnail without reading the whole image file: (C# - VB)
    Apply texture to bitmaps: (C# - VB)
    Extended console library: (VB)
    Save JPEG with a certain quality (image compression): (C# - VB )
    VB.NET to C# conversion tips!!

  10. #10

    Thread Starter
    Lively Member
    Join Date
    May 2003
    Posts
    98
    :O

    thats one complicated text box...

    what im doing is pasteing someting, and want to get only the nubmers in it

  11. #11
    l33t! MrPolite's Avatar
    Join Date
    Sep 2001
    Posts
    4,428
    here:

    VB Code:
    1. Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    2.         TextBox1.Text = filterText(TextBox1.Text)
    3.     End Sub
    4.  
    5.     Private Function filterText(ByVal txt As String) As String
    6.         If txt Is Nothing Then Return Nothing
    7.  
    8.         Const numbers As String = "1234567890"
    9.         Dim filtered As String = ""
    10.         Dim i As Integer
    11.         Dim aChar As String
    12.  
    13.  
    14.         For i = 0 To txt.Length - 1
    15.             aChar = txt.Substring(i, 1)
    16.  
    17.             ' See if this character is a number
    18.             If numbers.IndexOf(aChar) <> -1 Then
    19.                 filtered &= aChar
    20.             End If
    21.         Next
    22.  
    23.         Return filtered
    24.     End Function
    rate my posts if they help ya!
    Extract thumbnail without reading the whole image file: (C# - VB)
    Apply texture to bitmaps: (C# - VB)
    Extended console library: (VB)
    Save JPEG with a certain quality (image compression): (C# - VB )
    VB.NET to C# conversion tips!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width