Results 1 to 18 of 18

Thread: VB.NET 140 Textboxes Numbers Only

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jan 2021
    Posts
    144

    VB.NET 140 Textboxes Numbers Only

    Hi All,

    I am searching for an option (if one exists) that will allow me to make 140 textboxes to accept numbers only. I was hoping there was another way than adding to the handler:

    Code:
    Handles TextBox1.KeyPress, TextBox2.KeyPress, TextBox3.KeyPress (etc etc)
    I am using this on another form, but of course only checking approx 10 boxes, so its not a big deal. I continue my search.... but hope there is some kind of magic to this problem.

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    24,990

    Re: VB.NET 140 Textboxes Numbers Only


  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Jan 2021
    Posts
    144

    Re: VB.NET 140 Textboxes Numbers Only

    Thanks... Why am I getting an error on my generic 'Public Class Form1' when using this? I get the error on Form1_Load 'MyBase.Load'


    Quote Originally Posted by .paul. View Post

  4. #4
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    37,704

    Re: VB.NET 140 Textboxes Numbers Only

    Ultimately, you only have two choices:

    1) Use a different control that only allows numeric input. That's the solution that .Paul. gave you. An alternative would be to use the NumericUpDown control instead of a textbox.

    2) Hook up event handlers by some means. That super long Handles clause can look messy, but it will work. The alternative to that would be to hook up event handlers dynamically with AddHandler. This could be done in a loop such that the amount of code wouldn't look too large, but it ultimately does the same thing.

    Of the two alternatives, the first one is better in this case. One point to note about what .Paul. wrote is that he has code that deals with copy/paste, which you'd have to deal with anyways, and which wouldn't be very easy to deal with in those event handlers.
    My usual boring signature: Nothing

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Jan 2021
    Posts
    144

    Re: VB.NET 140 Textboxes Numbers Only

    Thanks for the info on this. I will play around with some of these options.


    Quote Originally Posted by Shaggy Hiker View Post
    Ultimately, you only have two choices:

    1) Use a different control that only allows numeric input. That's the solution that .Paul. gave you. An alternative would be to use the NumericUpDown control instead of a textbox.

    2) Hook up event handlers by some means. That super long Handles clause can look messy, but it will work. The alternative to that would be to hook up event handlers dynamically with AddHandler. This could be done in a loop such that the amount of code wouldn't look too large, but it ultimately does the same thing.

    Of the two alternatives, the first one is better in this case. One point to note about what .Paul. wrote is that he has code that deals with copy/paste, which you'd have to deal with anyways, and which wouldn't be very easy to deal with in those event handlers.

  6. #6
    Member
    Join Date
    Jan 2022
    Posts
    40

    Re: VB.NET 140 Textboxes Numbers Only

    Can you do something like this? Change "YourControl" to the container that your textboxs live, and add only key chars to the array that you want your users to press:
    Code:
    For Each ctl As Control In YourControl.Controls
        If TypeOf ctl Is TextBox Then
            Dim AllowKeys() As Char = {
                "1"c,
                "2"c,
                "3"c,
                "4"c}
            AddHandler DirectCast(ctl, TextBox).KeyPress, Sub(sdr As Object, kpe As KeyPressEventArgs)
    
                                                              If Not AllowKeys.Contains(kpe.KeyChar) Then
                                                                  kpe.Handled = True
                                                              End If
                                                          End Sub
    
        End If
    Next

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    37,704

    Re: VB.NET 140 Textboxes Numbers Only

    How will that deal with copy/paste?
    My usual boring signature: Nothing

  8. #8
    Member
    Join Date
    Jan 2022
    Posts
    40

    Re: VB.NET 140 Textboxes Numbers Only

    How will that deal with copy/paste?
    As is it will not input. You could extend it to allow the ctl+v keycode, and I feel ive done that before. No time to tinker at the moment.

  9. #9
    Member
    Join Date
    Jan 2022
    Posts
    40

    Re: VB.NET 140 Textboxes Numbers Only

    As is it will not input. You could extend it to allow the ctl+v keycode, and I feel ive done that before. No time to tinker at the moment.
    come to think of it, maybe it would allow the paste as i dont think the v press would count as a char.

  10. #10
    Member
    Join Date
    Jan 2022
    Posts
    40

    Re: VB.NET 140 Textboxes Numbers Only

    come to think of it, maybe it would allow the paste as i dont think the v press would count as a char.
    excuse the spam, but I had to know!

    As the code is, it will not paste with ctl+V, but you can do with mouseclick.

    if those are conditions that need to be dealt with then we could go down that road, will likely need to use the keydown and instead of using array of char, use array of keys. Im clocking out for the day.

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

    Re: VB.NET 140 Textboxes Numbers Only

    Using Ctrl+V is not the only way to paste into a control. Given that handling pasted data is fairly simple in a custom control, it's clear that a custom control is the superior option in this case, rather than a standard TextBox with event handlers. It's not even difficult to change over from using standard TextBoxes to a custom control. You simply open the designer code file and do a Replace All on the type name.

  12. #12
    Member
    Join Date
    Jan 2022
    Posts
    40

    Re: VB.NET 140 Textboxes Numbers Only

    True, if youre going as far as adding an event to all textboxs in a control and have to condition unwanted textboxs youre better off making a custom contol

    Code:
        Private Class tb
            Inherits TextBox
            Dim AllowKeys() As Char = {
                        "1"c, "2"c, "3"c, "4", "5"c, "6"c, "7"c, "8"c, "9"c, "0"c}
            Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
    
                If Not AllowKeys.Contains(e.KeyChar) Then
    
                    e.Handled = True
                End If
            End Sub
    
        End Class
    and create them
    Code:
            Dim FLPTxtBoxGroup As New FlowLayoutPanel With {
                .FlowDirection = FlowDirection.LeftToRight,
                .Dock = DockStyle.Fill,
                .AutoScroll = True}
            Controls.Add(FLPTxtBoxGroup)
            For i As Integer = 0 To 140
                Dim WonkyNumericalTextBox As New tb With {
                    .Name = "WonkyTextBox" & i.ToString}
    
                FLPTxtBoxGroup.Controls.Add(WonkyNumericalTextBox)
            Next

  13. #13
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    24,990

    Re: VB.NET 140 Textboxes Numbers Only

    Quote Originally Posted by vbdotnut View Post
    True, if youre going as far as adding an event to all textboxs in a control and have to condition unwanted textboxs youre better off making a custom contol

    Code:
        Private Class tb
            Inherits TextBox
            Dim AllowKeys() As Char = {
                        "1"c, "2"c, "3"c, "4", "5"c, "6"c, "7"c, "8"c, "9"c, "0"c}
            Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
    
                If Not AllowKeys.Contains(e.KeyChar) Then
    
                    e.Handled = True
                End If
            End Sub
    
        End Class
    and create them
    Code:
            Dim FLPTxtBoxGroup As New FlowLayoutPanel With {
                .FlowDirection = FlowDirection.LeftToRight,
                .Dock = DockStyle.Fill,
                .AutoScroll = True}
            Controls.Add(FLPTxtBoxGroup)
            For i As Integer = 0 To 140
                Dim WonkyNumericalTextBox As New tb With {
                    .Name = "WonkyTextBox" & i.ToString}
    
                FLPTxtBoxGroup.Controls.Add(WonkyNumericalTextBox)
            Next
    @vbdotnut
    “4” is a String 😎
    What about control keys? The extended TextBox I posted allows only numeric input AND control keys AND restricts non-numeric pasting…
    @OP Easy to add to your project and replace your existing TextBoxes, as jmcilhinney told you.

  14. #14
    Member
    Join Date
    Jan 2022
    Posts
    40

    Re: VB.NET 140 Textboxes Numbers Only

    “4” is a String
    Ha, youre right! I would have not caught that. Thinking Opt Strict was not on and that was inferred as char

  15. #15
    Member
    Join Date
    Jan 2022
    Posts
    40

    Re: VB.NET 140 Textboxes Numbers Only

    The extended TextBox I posted
    Hey Paul, im just wondering, why did you create that bit of code? Just curious as to why the textbox instead of just using numuericupdown

  16. #16
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    24,990

    Re: VB.NET 140 Textboxes Numbers Only

    Quote Originally Posted by vbdotnut View Post
    Hey Paul, im just wondering, why did you create that bit of code? Just curious as to why the textbox instead of just using numuericupdown
    Just because pasting is more controlled in my custom textbox...

  17. #17
    Frenzied Member PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Newport, UK
    Posts
    1,927

    Re: VB.NET 140 Textboxes Numbers Only

    Just dug up an old bit of sample code I threw together a few years ago, it is just another custom textbox.

    You can set the type of content allowed via the AllowedContent property and there is a CustomCharacters property you can use to allow / deny characters. There is also an InvalidCharacter event that is raised if there is an attempt to enter an invalid character.

    The custom control also enforces the AllowedContent when trying to assign text via the .Text property or when pasting.

    Been a while since I wrote this so apologies for any bugs that may be lurking.

    Code:
    Option Strict On
    
    Imports System.ComponentModel
    Imports System.Windows.Forms
    
    Public Class RestrictedTextBox
    	Inherits TextBox
    
    	'Event to raise when invalid content is attempted
    	Public Event InvalidCharacter As EventHandler(Of RestrictedTextBoxEventArgs)
    
    	'Enumeration of valid content types, use the Flags() attribute
    	'as this allows combinations to be defined.
    	<Flags()>
    	Public Enum AllowedContentTypes
    		Alphabetic = 1
    		Numeric = 2
    		Alphanumeric = 3
    		Punctuation = 4
    		PunctuatedAlphabetic = 5
    		Separators = 8
    		Symbols = 16
    		Any = 31
    		AllowCustom = 32
    		DenyCustom = 64
    	End Enum
    
    	<Description("Valid list of characters the control can contain, used when allowed content types is set to custom")>
    	Public Property CustomCharacters As String
    
    	'IDE Stuff
    	<Description("Defines the type of content the control can contain"),
    	Category("Behavior"), DefaultValue(GetType(AllowedContentTypes), "Any")>
    	Public Property AllowedContent() As AllowedContentTypes = AllowedContentTypes.Any
    
    
    	Protected Sub OnInvalidKeystroke(e As RestrictedTextBoxEventArgs)
    		RaiseEvent InvalidCharacter(Me, e)
    	End Sub
    
    	'when a key is pressed check if it should be allowed or not.
    	Private Sub RestrictedTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles MyBase.KeyPress
    
    		'Don't interfere with control codes (ctrl+v etc)
    		If Char.IsControl(e.KeyChar) Then Return
    
    		'Is this a valid character for the given content types
    		If ValidateCharacter(e.KeyChar) Then Return
    
    		'If keystroke hasn't been approved above then raise our event and 
    		'prevent further processing of the keystroke.
    		OnInvalidKeystroke(New RestrictedTextBoxEventArgs(e.KeyChar, AllowedContent))
    		e.Handled = True
    	End Sub
    
    	Private Function ValidateCharacter(c As Char) As Boolean
    
    		If AllowedContent.HasFlag(AllowedContentTypes.AllowCustom) AndAlso CustomCharacters.Contains(c) Then Return True
    		If AllowedContent.HasFlag(AllowedContentTypes.DenyCustom) AndAlso Not CustomCharacters.Contains(c) Then Return True
    
    		If AllowedContent.HasFlag(AllowedContentTypes.Numeric) AndAlso Char.IsNumber(c) Then Return True
    		If AllowedContent.HasFlag(AllowedContentTypes.Alphabetic) AndAlso Char.IsLetter(c) Then Return True
    		If AllowedContent.HasFlag(AllowedContentTypes.Punctuation) AndAlso Char.IsPunctuation(c) Then Return True
    		If AllowedContent.HasFlag(AllowedContentTypes.Separators) AndAlso Char.IsSeparator(c) Then Return True
    		If AllowedContent.HasFlag(AllowedContentTypes.Symbols) AndAlso Char.IsSymbol(c) Then Return True
    
    		Return False
    	End Function
    
    	Public Overrides Property Text() As String
    		Get
    			Return MyBase.Text
    		End Get
    		Set(value As String)
    			If ValidateString(value) Then
    				MyBase.Text = value
    			End If
    		End Set
    	End Property
    
    	'Really lame function to check the validity of a string, simply loops through
    	'each character till it finds an invalid one or reaches the end...
    	Private Function ValidateString(data As String) As Boolean
    
    		For Each c As Char In data
    			If ValidateCharacter(c) = False Then Return False
    		Next
    
    		Return True
    	End Function
    
    	'Another possible issue is people using Paste to enter invalid text, so we
    	'trap the relevant windows message and handle accordingly
    	Protected Overrides Sub WndProc(ByRef m As Message)
    
    		Const WM_PASTE As Integer = &H302
    
    		Select Case m.Msg
    			Case WM_PASTE
    				' Only interested if there is text based data so check that 1st
    				If Clipboard.GetDataObject.GetDataPresent(DataFormats.Text, True) Then
    					'If it is text, retrieve it and validate it
    					Dim tmp As String = Clipboard.GetDataObject.GetData(DataFormats.Text, True).ToString
    
    					'If valid perform the paste
    					If ValidateString(tmp) Then
    						MyBase.WndProc(m)
    					End If
    				End If
    			Case Else
    				'All other messages get dealt with by the default handler...
    				MyBase.WndProc(m)
    		End Select
    
    	End Sub
    End Class
    
    'EventArgs class for InvalidKeystroke event
    Public Class RestrictedTextBoxEventArgs
    	Inherits EventArgs
    
    	'Allow the handler to retrieve the invalid character
    	Public ReadOnly Property InvalidCharacter() As Char
    
    	'Return the allowed content types.
    	Public ReadOnly Property AllowedContent() As RestrictedTextBox.AllowedContentTypes
    
    	'constructor
    	Public Sub New(invalidCharacter As Char, allowedContent As RestrictedTextBox.AllowedContentTypes)
    		Me.InvalidCharacter = invalidCharacter
    		Me.AllowedContent = allowedContent
    	End Sub
    
    End Class

  18. #18
    Hyperactive Member Peter Porter's Avatar
    Join Date
    Jul 2013
    Posts
    473

    Re: VB.NET 140 Textboxes Numbers Only

    Quote Originally Posted by mikeg71 View Post
    Hi All,

    I am searching for an option (if one exists) that will allow me to make 140 textboxes to accept numbers only. I was hoping there was another way than adding to the handler:

    Code:
    Handles TextBox1.KeyPress, TextBox2.KeyPress, TextBox3.KeyPress (etc etc)
    I am using this on another form, but of course only checking approx 10 boxes, so its not a big deal. I continue my search.... but hope there is some kind of magic to this problem.

    Hey, Mike. Are all the textboxes visible on one form? How large a number can each one hold? Is it possible to show us an example of what it all looks like?

Tags for this Thread

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