Results 1 to 7 of 7

Thread: Numeric only textbox including scientific notation

  1. #1

    Thread Starter
    Fanatic Member Delaney's Avatar
    Join Date
    Nov 2019
    Location
    Paris, France
    Posts
    845

    Numeric only textbox including scientific notation

    Hello,

    EDIT : if you want to have the final version of the custom control, go to the last post.

    For one of my application, I had to restrict some textbox entry to numeric only but I accept scientific notation (so 1E5 is ok) and negative value (so the - sign is ok too) and as some of the users have a config that use coma and others that use dot as decimal separator, I dealt also with that. I wanted also that if you type any non valid key, nothing happen (in appearance )

    I created 2 functions and worked on the textchanged event.

    Function to Check that the text is a number
    Code:
        Public Function verif_nombre(ByVal text As String) As String
            Dim count As Integer 'To count the number of E
            Dim text_verifie As String = ""
            Dim l As Integer = text.Length
            If l = 0 Then Return text_verifie ' If there is no character, do go further, it is not needed
            Dim charac As Char = text.Chars(text.Length - 1) ' get the last character typed
    
            If charac = CChar("-") And text.Length = 1 Then ' deal with - sign
                Return text
            End If
    
            If text.Contains(" ") Then ' replace space by nothing
                text = text.Replace(" ", "")
                Return text
            End If
    
            'Count the number of e or E in the text
            If text.Contains("e") And text.Contains("E") Then
                count = 2
            ElseIf text.Contains("e") Then
                count = text.Split(CChar("e")).Length - 1
            ElseIf text.Contains("E") Then
                count = text.Split(CChar("E")).Length - 1
            End If
    
            If count = 1 And (charac = CChar("E") Or charac = CChar("e")) And l > 1 Then 'Deal with the scientific notation
                text_verifie = text
            Else
                If IsNumeric(text) Then ' verify that the text is  numeric
                    text_verifie = text
                Else
                    text = text.Remove(l - 1) 'if not then remove last charac typed
                    text_verifie = text
                End If
            End If
            Return text_verifie
        End Function

    Manage dot and coma for the number
    Code:
    Public Function gpv(ByVal text As String) As String 'GPV : gère point-virgule = manage dot - coma ;)
                    Dim nfi As NumberFormatInfo = NumberFormatInfo.CurrentInfo 'get the info on the decimal separator for the current user
            If nfi.NumberDecimalSeparator = "." Then 'if dot replace all coma by dot
                text = text.Replace(",", ".")
            Else 'if coma replace dot by coma
                text = text.Replace(".", ",")
            End If
            Return text
        End Function

    Method to manage the TextChanged event
    Code:
    Public Sub Numeric_TextBox_TextChanged(sender As Object, e As System.EventArgs)
            Dim TB As TextBox = CType(sender, TextBox)
            TB.Text = verif_nombre(gpv(TB.Text)).ToString
            TB.Select(TB.Text.Length, 0)
        End Sub
    On the loading of the forms I handle the event for all textbox based on a tag, if the tag = num then I change the event method

    Code:
    Private Sub Form_Load(sender As Object, e As System.EventArgs) Handles Me.Load
            For Each TB As TextBox In Me.Controls.OfType(Of TextBox)()
                If TB.Tag Is "num" Then
                    AddHandler TB.TextChanged, AddressOf Numeric_TextBox_TextChanged
                End If
            Next
        End Sub
    Last edited by Delaney; Jun 11th, 2020 at 07:42 AM. Reason: add some color
    The best friend of any programmer is a search engine
    "Don't wish it was easier, wish you were better. Don't wish for less problems, wish for more skills. Don't wish for less challenges, wish for more wisdom" (J. Rohn)
    “They did not know it was impossible so they did it” (Mark Twain)

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: Numeric only textbox including scientific notation

    I would suggest building the functionality into a custom class that inherits TextBox. You would then override the OnTextChanged method rather than handling the TextChanged event. You can then use your custom class directly on your forms instead of a regular TextBox. If you want to see an example of that, follow the CodeBank link in my signature below and check out my own Numeric Text Box thread. You might get some other ideas from that too. For one thing, it's not a great idea to use the TextChanged event for this sort of thing if you can avoid it. That event is raised after the Text property has already changed, so you then have to do bad things like change the Text again in the event handler, as you're doing. Prevention is almost always better than cure, i.e. prevent the Text changing in the first place, if the new value would be invalid.

  3. #3

    Thread Starter
    Fanatic Member Delaney's Avatar
    Join Date
    Nov 2019
    Location
    Paris, France
    Posts
    845

    Re: Numeric only textbox including scientific notation

    Thank you for your comments and ideas.

    I never did custom class that inherits something so time to learn.
    I will have a look to you thread and see how I can improve my code.

    Prevention is almost always better than cure
    so I guess, the KeyPress or KeyDown should be better.

    A question : When you create a new (user ?) control that inherits, is it possible to put it in the toolbox to be able to use it directly in the design window ? or do I have to call it through the code ?

    Regards
    The best friend of any programmer is a search engine
    "Don't wish it was easier, wish you were better. Don't wish for less problems, wish for more skills. Don't wish for less challenges, wish for more wisdom" (J. Rohn)
    “They did not know it was impossible so they did it” (Mark Twain)

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: Numeric only textbox including scientific notation

    Quote Originally Posted by Delaney View Post
    so I guess, the KeyPress or KeyDown should be better.
    Generally speaking, yes. In your case though, you have the added complication of having to allow the user to enter the "E" with no guarantee that they'll enter a digit after it, so you'll need some extra validation for that.
    Quote Originally Posted by Delaney View Post
    A question : When you create a new (user ?) control that inherits, is it possible to put it in the toolbox to be able to use it directly in the design window ? or do I have to call it through the code ?
    Anything that inherits Control, either directly or indirectly, is a control. A user control is actually something specific. It is a class that inherits UserControl and is used to create a group of child controls that can de used as a unit. For other controls, particularly those inheriting existing standard controls, are generally referred to as custom controls.

    Any class declared in your solution that inherits Component (Control inherits Component), either directly or indirectly, will be automatically added a a special group at the top of the Toolbox and can be used in that solution. If you want a custom control available to any solution, declare it in a library project, compile that and put the DLL in an appropriate location. You can then right-click the Toolbox and select Choose Items to select that library and your control. That's how you add any new controls or components to the Toolbox.

  5. #5

    Thread Starter
    Fanatic Member Delaney's Avatar
    Join Date
    Nov 2019
    Location
    Paris, France
    Posts
    845

    Re: Numeric only textbox including scientific notation

    Quote Originally Posted by jmcilhinney View Post
    Generally speaking, yes. In your case though, you have the added complication of having to allow the user to enter the "E" with no guarantee that they'll enter a digit after it, so you'll need some extra validation for that.
    .
    I forgot about this case (too much confidence in my users maybe...), I just tested it and get an error so I will have to correct that.

    And thank you for the explanation about user and custom control.

    regards
    The best friend of any programmer is a search engine
    "Don't wish it was easier, wish you were better. Don't wish for less problems, wish for more skills. Don't wish for less challenges, wish for more wisdom" (J. Rohn)
    “They did not know it was impossible so they did it” (Mark Twain)

  6. #6
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,042

    Re: Numeric only textbox including scientific notation

    Quote Originally Posted by Delaney View Post
    too much confidence in my users maybe...
    some User's are as Bad as toothache, the love to-Copy&Paste-
    so consider that also

    EDIT:
    here a few thoughts

    Code:
    Public Class Form1
    
        Private Sub TextBox1_Enter(sender As Object, e As System.EventArgs) Handles TextBox1.Enter
            'to prevent Copy&Paste
            Clipboard.Clear()
        End Sub
    
        Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
            If e.KeyChar = "."c Then
                'allow only one .
                e.Handled = (CType(sender, TextBox).Text.IndexOf("."c) <> -1)
            ElseIf e.KeyChar = "E"c Then
                'allow only one E
                e.Handled = (CType(sender, TextBox).Text.IndexOf("E"c) <> -1)
                'allow Backspace
            ElseIf e.KeyChar <> ControlChars.Back Then
                e.Handled = ("0123456789AaEe".IndexOf(e.KeyChar) = -1)  '<--allowed
            End If
        End Sub
    
    End Class
    I haven't tried what JMC discribes in Post#2, I would need something like that
    for a -Date Textbox- and a -Time Textbox- or probably combine those
    Last edited by ChrisE; May 30th, 2020 at 05:16 AM.
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  7. #7

    Thread Starter
    Fanatic Member Delaney's Avatar
    Join Date
    Nov 2019
    Location
    Paris, France
    Posts
    845

    Re: Numeric only textbox including scientific notation

    Here is my update,

    I created a custom textbox on the advice of jmcilhinney. That helped me a lot, thanks John. I will be able to put that very easily in all my applications.

    I still use the TextChanged event which allows to use copy/paste and will correct it in a very drastic way.
    I use also the Leave event, so I can deal with the "E" without a digit after.
    I take care also of the use of minus sign as last digit (i.e "12-" recognized by Vb.net as numeric).

    So I accept the following : (the number of x is not contractual, you can have more but the number of y is linked to the size of a double)
    xxx
    xxx.xx or xxx,xx depending of user setting
    -xxx
    -xxx.xx or -xxx,xxx depending of user setting
    xxeyy or xxEyy
    xxe-yy or xxE-yy
    or any combination of above (no, you can't have xxeEYY )
    You cannot leave the textbox if it ends by "e" or "E" (122E for example).

    It has been written in VB.net 2010 because I will use it mainly for my work as I have VB 2010 on my office desktop computer.

    The files :
    Numeric_TextBox.vb : the custom control
    Numeric_TB_example.zip : Example

    Regards

    Cyril
    Last edited by Delaney; Jun 11th, 2020 at 07:41 AM.
    The best friend of any programmer is a search engine
    "Don't wish it was easier, wish you were better. Don't wish for less problems, wish for more skills. Don't wish for less challenges, wish for more wisdom" (J. Rohn)
    “They did not know it was impossible so they did it” (Mark Twain)

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