PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
[RESOLVED] Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals-VBForums
Results 1 to 20 of 20

Thread: [RESOLVED] Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

  1. #1

    Thread Starter
    Junior Member
    Join Date
    May 2020
    Posts
    18

    Resolved [RESOLVED] Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    I have searched for this and have not found something that works for my needs.

    I have 30+ textboxes on a form that I want to have the following restrictions:

    - Numbers only
    - Negatives allowed
    - No decimals
    - Backspace/delete allowed

    Can this validation be done on ALL textboxes without doing individual calls for each textbox? Trying to keep code to a minimum.

  2. #2
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    32,793

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    Or... instead of textboxes, you use the Numeric UpDown control... that's all built in.
    AND, it'll handle copy/paste situations for you too.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  3. #3
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,410

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    Instead of a TextBox, use a NumericUpDown.

    A NumericUpDown is basically a textbox for entering numbers only, and you can set various properties of the control to adjust its behaviour - such as allowing decimals or not, setting the min/max values allowed (you can use negative values for them if you want), and whether or not to have up/down arrows displayed next to it (which you can click on to increase/decrease the value).

  4. #4

    Thread Starter
    Junior Member
    Join Date
    May 2020
    Posts
    18

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    From a UX perspective, the NumericUpDown controls are not great. When tabbing through, you have to clear the 0 to enter a number otherwise you get the 0 tagged on to the end. Also, setting them to accept negatives is a pain.

  5. #5
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    23,121

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    I'd use an extended NumericUpDown control. You can set the properties that are consistently the same in all of your controls in sub new. You can handle the Enter (such as tab to) and Click events so if on gaining focus, the value of the NumericUpDown is zero, it'll be highlighted and you can just type straight over it...

    Code:
    Public Class NumericUpDownEx
        Inherits NumericUpDown
    
        Public Sub New()
            MyBase.Minimum = -100
            MyBase.Maximum = 100
            MyBase.DecimalPlaces = 0
            MyBase.Controls(0).Visible = False
        End Sub
    
        Protected Overrides Sub OnEnter(ByVal e As System.EventArgs)
            If MyBase.Value = 0D Then
                MyBase.Select(0, 1)
            End If
            MyBase.OnEnter(e)
        End Sub
    
        Protected Overrides Sub OnClick(ByVal e As System.EventArgs)
            If MyBase.Value = 0D Then
                MyBase.Select(0, 1)
            End If
            MyBase.OnClick(e)
        End Sub
    
    End Class

  6. #6

    Thread Starter
    Junior Member
    Join Date
    May 2020
    Posts
    18

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    Where do I place this code? I tried putting it into my form's public class and it has not effect.

  7. #7
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    23,121

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    Project—>Add New Class

    Name it NumericUpDownEx, then edit it to resemble what I posted. Run your project in the IDE then stop it. You’ll find the NumericUpDownEx control at the top of your toolbox, and you add it as you would any control...

  8. #8

    Thread Starter
    Junior Member
    Join Date
    May 2020
    Posts
    18

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    Thanks. I seem to have it working.

    Is there any way to completely remove the arrow? Hiding them still leaves the grey background where they were.

    Also, is there a way to allow it to be empty when the number is 0?

  9. #9
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    104,681

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    You might like to check out this CodeBank thread of mine:

    http://www.vbforums.com/showthread.p...meric-Text-Box

  10. #10

    Thread Starter
    Junior Member
    Join Date
    May 2020
    Posts
    18

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    So, things actually get a bit more complicated and it appears I am a little over my head in this...

    I have 25 textboxes that need to be numbers only, positive and negative, no zeros allowed.

    There are another 25 textboxes that need to be numbers only, positive only, no zeros allowed.

    Can this be done without having to write code for 50 separate textboxes?
    Last edited by Velcrobelly; May 23rd, 2020 at 11:46 AM.

  11. #11
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    104,681

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    Quote Originally Posted by Velcrobelly View Post
    I guess the bottom line is that I can't have the input be 0...
    If only someone had posted a link to a custom control that could handle that.

  12. #12
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    23,121

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    @Velcrobelly - please keep the coding questions in the forum.

    Jm’s solution would probably be better for your requirements. I haven’t looked at it, but I read the description, and it looks like what you want. It can optionally allow negative numbers, optionally not show zero values. I’m just not sure if it can disallow decimals...

  13. #13
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    104,681

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    Quote Originally Posted by .paul. View Post
    Jm’s solution would probably be better for your requirements. I haven’t looked at it, but I read the description, and it looks like what you want. It can optionally allow negative numbers, optionally not show zero values. I’m just not sure if it can disallow decimals...
    I gotcha covered:
    * Text property hidden and data exposed via Value (Decimal) and NullableValue (Decimal?) properties
    * Optionally makes a sound when invalid input is rejected
    * Optionally accepts a negative sign
    * Optionally accepts a decimal point
    * Optionally allows blank input
    * Optionally converts blank input to zero automatically
    * Optionally allows standard or custom numeric format string
    * Optionally allows non-default culture formatting rules
    * Allows pasting of formatted text.

  14. #14
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    23,121

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    @Velcrobelly - It's just an extended control, like the one I showed you how to make, but it has some properties you need to set...

  15. #15

    Thread Starter
    Junior Member
    Join Date
    May 2020
    Posts
    18

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    @jmcilhinney I have your solution working for the most part. I cannot figure out how to not have a value of zero...

  16. #16
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    104,681

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    Quote Originally Posted by Velcrobelly View Post
    So, things actually get a bit more complicated and it appears I am a little over my head in this...

    I have 25 textboxes that need to be numbers only, positive and negative, no zeros allowed.

    There are another 25 textboxes that need to be numbers only, positive only, no zeros allowed.

    Can this be done without having to write code for 50 separate textboxes?
    The "no zeroes allowed" part complicates things a little. You could modify my NumberBox class to not allow a 0 unless there were already other digits present but I'd suggest that if you want to allow blank but not zero then you simply handle the Leave event and convert zero to blank, e.g.
    vb.net Code:
    1. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    2.     For Each nb In Controls.OfType(Of NumberBox)
    3.         AddHandler nb.Leave, AddressOf NumberBoxes_Leave
    4.     Next
    5. End Sub
    6.  
    7. Private Sub NumberBoxes_Leave(sender As Object, e As EventArgs)
    8.     Dim nb = DirectCast(sender, NumberBox)
    9.  
    10.     If nb.NullableValue = 0D Then
    11.         nb.NullableValue = Nothing
    12.     End If
    13. End Sub
    Last edited by jmcilhinney; May 23rd, 2020 at 12:37 PM.

  17. #17

    Thread Starter
    Junior Member
    Join Date
    May 2020
    Posts
    18

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    @jmcilhinney This works great! However, I did make an error on my specs above...

    The first 25 cannot be 0, null, or negative, so instead of "nb.NullableValue = Nothing" I changed it to "nb.NullableValue = 1".

    The second set of 25 can be 0 or null. How can I differentiate between the two sets?

  18. #18
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    104,681

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    Quote Originally Posted by jmcilhinney View Post
    You could modify my NumberBox class to not allow a 0 unless there were already other digits present but I'd suggest that if you want to allow blank but not zero then you simply handle the Leave event and convert zero to blank
    Another option occurred to me. You could add a ConvertFromZero option to the BlankMode property that would work the opposite way to ConvertToZero. I haven't tested this rigorously but I updated the nested BlankModes enumeration like so:
    vb.net Code:
    1. ''' <summary>
    2. ''' Defines constants that indicate how blank text is treated when a <see cref="NumberBox" /> loses focus.
    3. ''' </summary>
    4. Public Enum BlankModes
    5.     ''' <summary>
    6.     ''' Indicates that blank text is accepted.
    7.     ''' </summary>
    8.     <Description("Accept")> _
    9.     Accept
    10.     ''' <summary>
    11.     ''' Indicates that zero is converted to blank text.
    12.     ''' </summary>
    13.     <Description("Convert from Zero")>
    14.     ConvertFromZero
    15.     ''' <summary>
    16.     ''' Indicates that blank text is converted to zero.
    17.     ''' </summary>
    18.     <Description("Convert to Zero")>
    19.     ConvertToZero
    20.     ''' <summary>
    21.     ''' Indicates that an exception is thrown.
    22.     ''' </summary>
    23.     <Description("Reject")> _
    24.     Reject
    25. End Enum
    the BlankMode property like so:
    vb.net Code:
    1. ''' <summary>
    2. ''' Gets or sets a value indicating how blank text is treated when the form loses focus.
    3. ''' The default is <see cref="BlankModes.Accept">Accept</see>.
    4. ''' </summary>
    5. ''' <value>
    6. ''' One of the <see cref="BlankModes" /> values.
    7. ''' </value>
    8. ''' <remarks>
    9. ''' If this property is set to <see cref="BlankModes.Reject">Reject</see> and the control is blank when the user tries to close the form, the form will not close.
    10. ''' In this case, it is recommended to handle the <see cref="Form.FormClosing">FormClosing</see> event of the form and explicitly set <see cref="FormClosingEventArgs.Cancel">Cancel</see> to <b>false</b>.
    11. ''' Doing so will allow the form to close without the user having to enter a value that won't be used.
    12. ''' </remarks>
    13. <Category("Behavior"), _
    14. Description("Indicates how blank text is treated."), _
    15. DefaultValue(BlankModes.Accept)> _
    16. Public Property BlankMode() As BlankModes
    17.     Get
    18.         Return Me._blankMode
    19.     End Get
    20.     Set(ByVal value As BlankModes)
    21.         If Me._blankMode <> value Then
    22.             Me._blankMode = value
    23.  
    24.             'Raise the BlankModeChanged event.
    25.             Me.OnBlankModeChanged(EventArgs.Empty)
    26.  
    27.             If Not Me.Focused Then
    28.                 Select Case value
    29.                     Case BlankModes.ConvertFromZero
    30.                         If Me.NullableValue = Decimal.Zero Then
    31.                             Me.NullableValue = Nothing
    32.                         End If
    33.                     Case BlankModes.ConvertToZero, BlankModes.Reject
    34.                         'Convert blank text to zero.
    35.                         If Not Me.NullableValue.HasValue Then
    36.                             Me.NullableValue = Decimal.Zero
    37.                         End If
    38.                 End Select
    39.             End If
    40.         End If
    41.     End Set
    42. End Property
    the DisplayNumber method like so:
    vb.net Code:
    1. ''' <summary>
    2. ''' Displays a number using the appropriate formatting.
    3. ''' </summary>
    4. ''' <param name="number">
    5. ''' The number to display.
    6. ''' </param>
    7. ''' <param name="applyFormatting">
    8. ''' Indicates whether formatting should be applied.
    9. ''' </param>
    10. Private Sub DisplayNumber(ByVal number As Decimal?, ByVal applyFormatting As Boolean)
    11.     If (Not number.HasValue AndAlso Me.BlankMode = BlankModes.Accept) OrElse
    12.        (number = Decimal.Zero AndAlso Me.BlankMode = BlankModes.ConvertFromZero) Then
    13.         'There is no number to display.
    14.         Me.Text = String.Empty
    15.     ElseIf number.HasValue OrElse Me.BlankMode <> BlankModes.Reject Then
    16.         'Display the value if there is one or zero for a blank value.
    17.         Dim numberToDisplay As Decimal = If(number, Decimal.Zero)
    18.  
    19.         If Not Me.AllowDecimal Then
    20.             'Remove the decimal portion if there is one.
    21.             numberToDisplay = Decimal.Truncate(numberToDisplay)
    22.         End If
    23.  
    24.         If Not Me.AllowNegative Then
    25.             'Remove the negative sign if there is one.
    26.             numberToDisplay = Math.Abs(numberToDisplay)
    27.         End If
    28.  
    29.         Dim format As String = If(applyFormatting, _
    30.                                   Me.Format, _
    31.                                   Nothing)
    32.  
    33.         Me.Text = numberToDisplay.ToString(format, Me.FormatProvider)
    34.     End If
    35. End Sub
    and the ValidateNumber method like so:
    vb.net Code:
    1. ''' <summary>
    2. ''' Validates the specified number.
    3. ''' </summary>
    4. ''' <param name="number">
    5. ''' The proposed number.
    6. ''' </param>
    7. ''' <returns>
    8. ''' <b>true</b> if the number is valid; otherwise, <b>false</b>.
    9. ''' </returns>
    10. Private Function ValidateNumber(ByVal number As Decimal?) As Boolean
    11.     Dim isValid As Boolean
    12.  
    13.     If number.HasValue Then
    14.         Dim value = number.Value
    15.  
    16.         'Confirm that the number satisfies the current rules.
    17.         isValid = (value >= Decimal.Zero OrElse Me.AllowNegative) AndAlso _
    18.                   (value = Decimal.Truncate(value) OrElse Me.AllowDecimal)
    19.     Else
    20.         'Confirm that blank values are allowed.
    21.         isValid = (Me.BlankMode = BlankModes.Accept) OrElse (Me.BlankMode = BlankModes.ConvertFromZero)
    22.     End If
    23.  
    24.     If Not isValid Then
    25.         Me.PlayInvalidInputSound()
    26.     End If
    27.  
    28.     Return isValid
    29. End Function
    and it seemed to work.

    By the way, I should point out that that BlankModes enumeration is incorrectly named and it should actually be BlankMode, i.e. singular rather than plural. Enumerations should only have plural names if they have the Flags attribute applied and values of powers of 2 to allow multiple values to be combined.

  19. #19
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    104,681

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    Quote Originally Posted by Velcrobelly View Post
    How can I differentiate between the two sets?
    Add two Panels to your form and then add one set to one Panel and the other set to the other Panel. You can then loop through the Controls collections of the two Panels separately and attach a different event handler for each set.

  20. #20

    Thread Starter
    Junior Member
    Join Date
    May 2020
    Posts
    18

    Re: Multiple TextBoxes - Numbers Only, Negatives Allowed, No Decimals

    I got this to work pretty easily by putting the first set in a panel and changed the above to:

    For Each nb In Panel1.Controls.OfType(Of NumberBox)

    So that only runs on the one set. The other fields are handled by the original class you created.

    Thanks, everyone so much for your help!

Posting Permissions

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



Featured


Click Here to Expand Forum to Full Width