locked
Digit grouping the number when I am enter it RRS feed

  • Question

  • I have a program that calculate the loan interest. I have several text box for entering loan amount and other information. I want that when the user is entering the amount in text boxes it group the digits (Like 30,000,456). it is most readable. I tries some ways but it doesn't worked.

    My program is a windows form application.

    regards,

     

    Karim Vaziri Regards,

    Tuesday, February 27, 2018 9:48 PM

Answers

  • Hi,

    I made a sample:
         

    ' --- Format Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged If (Me.TextBox1.Text.Length > 0) Then ' --- triple digit Dim myNumeric As Integer = CInt(Me.TextBox1.Text) Me.TextBox1.Text = String.Format("{0:#,0}", myNumeric) ' --- place input caret to the last Me.TextBox1.SelectionStart = Me.TextBox1.Text.Length End If End Sub

    ' --- Numeric only: 0-9 or [BackSpace] is OK Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress If (e.KeyChar < "0"c OrElse "9"c < e.KeyChar) AndAlso (e.KeyChar <> ControlChars.Back) Then e.Handled = True End If End Sub

    In event "TextBox1.TextChanged", TextBox1 is formatted with triple-digit.
    (that's an answer to your question)

    In event "TextBox1.KeyPress", input character is limited to [0]-[9] and [Back Space]. 
    (this is optional)

    Regards,

    Ashidacchi

    • Proposed as answer by KareninstructorMVP Wednesday, February 28, 2018 1:46 AM
    • Edited by Ashidacchi Wednesday, February 28, 2018 1:59 AM
    • Marked as answer by kvaziri Friday, March 2, 2018 7:19 PM
    Wednesday, February 28, 2018 12:56 AM

All replies

  • Please show what you have tried so that they are not suggestions back to you.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, February 27, 2018 9:54 PM
  • Do the group separators have to appear as you type?  That can get messy depending on where the mouse is positioned, accounting for pasted values, etc.

    If it is OK for the value to format itself after the user is done typing and the textbox looses focus, then use the Validating event of the textbox to apply formatting.  Since these are currency values I would suggest using ToString("C") on the parsed decimal value.  Something like:

    Private Sub TextBox1_Validating(sender As Object, e As CancelEventArgs) Handles TextBox1.Validating
        If TextBox1.TextLength > 0 Then
            Dim decimalValue As Decimal
            If Not Decimal.TryParse(TextBox1.Text, decimalValue) Then
                TextBox1.SelectAll()
                e.Cancel = True
            Else
                TextBox1.Text = decimalValue.ToString("C")
            End If
        End If
    End Sub
    

     

    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Tuesday, February 27, 2018 9:58 PM
  • Hi,

    I made a sample:
         

    ' --- Format Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged If (Me.TextBox1.Text.Length > 0) Then ' --- triple digit Dim myNumeric As Integer = CInt(Me.TextBox1.Text) Me.TextBox1.Text = String.Format("{0:#,0}", myNumeric) ' --- place input caret to the last Me.TextBox1.SelectionStart = Me.TextBox1.Text.Length End If End Sub

    ' --- Numeric only: 0-9 or [BackSpace] is OK Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress If (e.KeyChar < "0"c OrElse "9"c < e.KeyChar) AndAlso (e.KeyChar <> ControlChars.Back) Then e.Handled = True End If End Sub

    In event "TextBox1.TextChanged", TextBox1 is formatted with triple-digit.
    (that's an answer to your question)

    In event "TextBox1.KeyPress", input character is limited to [0]-[9] and [Back Space]. 
    (this is optional)

    Regards,

    Ashidacchi

    • Proposed as answer by KareninstructorMVP Wednesday, February 28, 2018 1:46 AM
    • Edited by Ashidacchi Wednesday, February 28, 2018 1:59 AM
    • Marked as answer by kvaziri Friday, March 2, 2018 7:19 PM
    Wednesday, February 28, 2018 12:56 AM
  • Here is a version done using Ashidacchi logic in a custom TextBox. Prevents a-z to be pasted from the clipboard.

    Public Class SpecialTextbox
        Inherits TextBox
        Public Sub New()
            TextAlign = HorizontalAlignment.Right
        End Sub
    
        Protected Overrides Sub OnTextChanged(e As EventArgs)
            MyBase.OnTextChanged(e)
    
            If (Text.Length > 0) Then
                Dim decValue As Decimal = 0
                Decimal.TryParse(Text, decValue)
                Text = $"{decValue:#,0}"
    
                SelectionStart = Text.Length
    
            End If
        End Sub
        Const WM_PASTE As Integer = &H302
        Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
            Dim value As String = Text
            value = value.Remove(SelectionStart, SelectionLength)
            value = value.Insert(SelectionStart, e.KeyChar)
            e.Handled = CBool(value.LastIndexOf("-", StringComparison.Ordinal) > 0) Or
                Not (Char.IsControl(e.KeyChar) OrElse Char.IsDigit(e.KeyChar) OrElse
                     (e.KeyChar = "."c And
                      Not Text.Contains(".") Or e.KeyChar = "."c And
                      SelectedText.Contains(".")) OrElse (e.KeyChar = "-"c And
                                                             SelectionStart = 0))
    
            MyBase.OnKeyPress(e)
        End Sub
        Protected Overrides Sub WndProc(ByRef m As Message)
            If m.Msg = WM_PASTE Then
                Dim value As String = Text
                value = value.Remove(SelectionStart, SelectionLength)
                value = value.Insert(SelectionStart, Clipboard.GetText)
                Dim result As Decimal = 0
                If Not Decimal.TryParse(value, result) Then
                    Return
                End If
            End If
    
            MyBase.WndProc(m)
    
        End Sub
    End Class
    Place it in the project, compile and it will be available at the top of the ToolBox.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, February 28, 2018 1:46 AM
  • Karen, you also allowed for typing in the middle of a number, dealing with decimals and allowing negatives.  That takes care of a lot of the difficulties that come with just trying to trap key presses (especially with the paste handling code).

    Other considerations are the currency symbol and regional differences (instead of a hard coded period and comma, it should be the current culture digit separators).

    But this is why I always shy away from this kind of solution in preference of the Validating event - there are so many little issues to be concerned with.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Wednesday, February 28, 2018 2:42 AM
  • Reed,

    In regards to culture that indeed should be thought of for the targeted audience if applicable. 


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, February 28, 2018 3:08 AM
  • Hi kvaziri,

    You can take a look the following code:

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
            Dim value As String = TextBox1.Text.Replace(",", "")
            Dim ul As Double
            If Double.TryParse(value, ul) Then
                TextBox1.Text = String.Format("{0:#,#}", ul)
                TextBox1.SelectionStart = TextBox1.Text.Length
            End If
        End Sub

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, February 28, 2018 5:45 AM
  • Dear Ashidacchi,

    It is fantastic and what I need. But there is a problem, my application is a financial app and I need this formatting for a lot of text boxes that the operator enter digits, and I should repeat this routine for any textbox, is there any function or way that I don't need to repeat it for any textbox.


    Karim Vaziri Regards,

    Friday, March 2, 2018 7:23 PM
  • Dear Reed,

    Your solution is helpful for digit grouping when the text box lose focus. But I need that the program separates the digits when the user is typing amount in textbox  and help him or her  to don't put extra or less zero in entered amount, but I use it in other cases.

    Thanks a lot.


    Karim Vaziri Regards,

    Friday, March 2, 2018 7:38 PM
  • Dear Reed,

    Your solution is helpful for digit grouping when the text box lose focus. But I need that the program separates the digits when the user is typing amount in textbox  and help him or her  to don't put extra or less zero in entered amount, but I use it in other cases.

    Thanks a lot.


    Karim Vaziri Regards,


    Then you should use Karen's example and mark her post as answer as well.  It takes extra code to handle things like the user pasting from the clipboard or if they try to type over part of an existing number.

    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Friday, March 2, 2018 8:17 PM