none
how to add commas after every 3 digit in vb.net? RRS feed

  • Question

  • Hello,

    I'm having a problem on how to do display commas after every 3 digits in my textbox. I don't typed in the value in the textbox I'm using a button to insert the numbers. Honestly I have read the docs and search the internet on how to do this right but I don''t really get it.

    I already read this Custom numeric format strings and this String format I'm already frustrated about this.

    Here is the code that I'm using to insert the numbers inside the textbox:

      Private Sub btnNumbers(sender As Object, e As EventArgs) Handles btn0.Click, btn1.Click, btn2.Click, btn3.Click, btn4.Click, btn5.Click, btn6.Click, btn7.Click, btn8.Click, btn9.Click, btnDecimal.Click
    
            Dim btnB As Guna.UI.WinForms.GunaButton = DirectCast(sender, Guna.UI.WinForms.GunaButton)
    
    
            If txtInput.Text.Length >= txtInput.MaxLength Then
    
    
                Exit Sub
    
            Else
    
                If txtInput.Text = "0" Or expression Then
    
                    txtInput.Text = ""
                    txtInput.Text = btnB.Text
                    expression = False
    
                ElseIf btnB.Text = "." Then
    
                    If Not txtInput.Text.Contains(".") Then
    
                        txtInput.Text = txtInput.Text + btnB.Text
    
                    End If
    
                Else
                  
                    txtInput.Text = txtInput.Text + btnB.Text
    
                End If
    
    
            End If
    
    
        End Sub


    And here is the code that I'm trying to use to add commas after 3 digits but I can't get it working

            txtInput.Text = txtInput.Text + btnB.Text
            Dim value As Integer = Convert.ToInt32(txtInput.Text)
            txtInput.Text = value.ToString("N0")

    After inserting 4 digits like 1,000 it throws an exception: System.FormatException: 'Input string was not in a correct format. The exception is pointing to the line that is bold and have underline.

    I'm really lost. I tried to understand the docs but I don't get it jeez really frustrating.


    • Edited by lelouch_vi Friday, May 22, 2020 1:32 PM
    Friday, May 22, 2020 10:09 AM

Answers

  • Hi lelouch_vi,

    In order to add commas after every 3 digit in TextBox, you can try the following code:

        Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
            TextBox1.SelectionStart = TextBox1.Text.Length
    
            If TextBox1.Text.Contains("."c) Then
    
                If TextBox1.Text.IndexOf(".") = TextBox1.Text.LastIndexOf(".") Then
                Else
                    TextBox1.Text = TextBox1.Text.Remove(TextBox1.Text.Length - 1)
                End If
            Else
                TextBox1.Text = String.Format("{0:n0}", Convert.ToDecimal(TextBox1.Text.Replace(",", "")))
            End If
        End Sub

    Result of my test:

    Hope it can help you.

    Best Regards,

    Xingyu Zhao


    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.

    • Marked as answer by lelouch_vi Thursday, May 28, 2020 4:59 AM
    Tuesday, May 26, 2020 2:35 AM
    Moderator

All replies

  • Hi

    There are many ways to tackle such an issue. Here s one way (very simple)

    This version just ignortes any invalid characters the User may enter. Other ways to deal with invalid characters are available.

    THIS is a good link.

      Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        ' TEXTBOX1 used for this example
        Try
          With TextBox1
            .Text = FormatNumber(.Text, 0, TriState.True, TriState.UseDefault, TriState.UseDefault)
            .SelectionLength = 0
            .SelectionStart = .Text.Length
          End With
        Catch ex As InvalidCastException
          '  skip invalid characters
        End Try
      End Sub


    Regards Les, Livingston, Scotland





    • Edited by leshay Friday, May 22, 2020 12:23 PM
    Friday, May 22, 2020 11:53 AM
  • Hi elouch_vi

    You need check the input number before apply formatting and I have changed the if conditions.

     Dim btnB As Guna.UI.WinForms.GunaButton = DirectCast(sender, Guna.UI.WinForms.GunaButton)
    
    
            Dim result1 As Integer
            Dim result2 As Decimal
    
    
            If txtInput.Text.Length >= txtInput.MaxLength Then
    
    
                Exit Sub
    
            Else
    
                If txtInput.Text = "0" Or expression Then
    
                    txtInput.Text = ""
                    txtInput.Text = btnB.Text
                    expression = False
    
    
    
                ElseIf Int32.TryParse(txtInput.Text, result1) Then
    
    
    
                    result1 = txtInput.Text + btnB.Text
    
                    Dim value As Integer = Convert.ToInt32(result1)
                    txtInput.Text = value.ToString("N0")
    
    
    
                ElseIf Decimal.TryParse(txtInput.Text, result2) Then
    
                    result2 = txtInput.Text + btnB.Text
    
                    Dim value As Decimal = Convert.ToDecimal(result2)
                    txtInput.Text = value.ToString("N3")
    
                End If
    
    
            End If



    Please remember to mark the replies as answers if they helped you :) ~



    Friday, May 22, 2020 11:55 AM
  • Convert.ToInt32 won't work if the input string contains the thousands separator.

    Try:

    Hide   Copy Code
    Dim value As Ineger = Integer.Parse(txtInput.Text, System.Globalization.NumberStyles.Integer Or System.Globalization.NumberStyles.AllowThousands)
    txtInput.Text = value.ToString("N0")
    Int32.Parse Method (System) | Microsoft Docs[^]
    NumberStyles Enum (System.Globalization) | Microsoft Docs[^]



    I hope this helps!


    Friday, May 22, 2020 12:32 PM
  • Hi elouch_vi

    You need check the input number before apply formatting and I have changed the if conditions.

     Dim btnB As Guna.UI.WinForms.GunaButton = DirectCast(sender, Guna.UI.WinForms.GunaButton)
    
    
            Dim result1 As Integer
            Dim result2 As Decimal
    
    
            If txtInput.Text.Length >= txtInput.MaxLength Then
    
    
                Exit Sub
    
            Else
    
                If txtInput.Text = "0" Or expression Then
    
                    txtInput.Text = ""
                    txtInput.Text = btnB.Text
                    expression = False
    
    
    
                ElseIf Int32.TryParse(txtInput.Text, result1) Then
    
    
    
                    result1 = txtInput.Text + btnB.Text
    
                    Dim value As Integer = Convert.ToInt32(result1)
                    txtInput.Text = value.ToString("N0")
    
    
    
                ElseIf Decimal.TryParse(txtInput.Text, result2) Then
    
                    result2 = txtInput.Text + btnB.Text
    
                    Dim value As Decimal = Convert.ToDecimal(result2)
                    txtInput.Text = value.ToString("N3")
    
                End If
    
    
            End If



    Please remember to mark the replies as answers if they helped you :) ~



    Hi Rebin Qadir,

    I tried the above code but sad to say it doesn't even display the numbers that I pressed. Also I want my input to include a decimal value not just whole numbers  but thanks anyway for trying to help me. Appreciate it.

    Friday, May 22, 2020 1:28 PM
  • Hi

    There are many ways to tackle such an issue. Here s one way (very simple)

    This version just ignortes any invalid characters the User may enter. Other ways to deal with invalid characters are available.

    THIS is a good link.

      Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        ' TEXTBOX1 used for this example
        Try
          With TextBox1
            .Text = FormatNumber(.Text, 0, TriState.True, TriState.UseDefault, TriState.UseDefault)
            .SelectionLength = 0
            .SelectionStart = .Text.Length
          End With
        Catch ex As InvalidCastException
          '  skip invalid characters
        End Try
      End Sub


    Regards Les, Livingston, Scotland





    Hi leshay,

    I'm attaching the gif of my project

    As you can see the buttons are working fine I can add a decimal value. All I want is a comma after every 3 digits so it can look better plus I'll still be needing the numbers in the textbox for computation since I'm making a calculator. Thanks for future help. 

    Friday, May 22, 2020 1:54 PM
  • Hi

    There are many ways to tackle such an issue. Here s one way (very simple)

    This version just ignortes any invalid characters the User may enter. Other ways to deal with invalid characters are available.

    THIS is a good link.

      Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        ' TEXTBOX1 used for this example
        Try
          With TextBox1
            .Text = FormatNumber(.Text, 0, TriState.True, TriState.UseDefault, TriState.UseDefault)
            .SelectionLength = 0
            .SelectionStart = .Text.Length
          End With
        Catch ex As InvalidCastException
          '  skip invalid characters
        End Try
      End Sub


    Regards Les, Livingston, Scotland





    Hi leshay,

    I'm attaching the gif of my project

    As you can see the buttons are working fine I can add a decimal value. All I want is a comma after every 3 digits so it can look better plus I'll still be needing the numbers in the textbox for computation since I'm making a calculator. Thanks for future help. 

    Hi

    Did you try adding the Sub from my postto your code? Obviously, adjust for the actual TextBox in your project if not TextBox1.


    Regards Les, Livingston, Scotland


    • Edited by leshay Friday, May 22, 2020 2:01 PM
    Friday, May 22, 2020 2:00 PM
  • Hi

    Did you try adding the Sub from my postto your code?


    Regards Les, Livingston, Scotland

    Hi leshay,

    Here is my code after incorporating your given solution earlier. Inserting a decimal value is not working again, please have a look

       If txtInput.Text.Length >= txtInput.MaxLength Then
    
    
                Exit Sub
    
            Else
    
                If txtInput.Text = "0" Or expression Then
    
                    txtInput.Text = ""
                    txtInput.Text = btnB.Text
                    expression = False
    
                ElseIf btnB.Text = "." Then
    
                    If Not txtInput.Text.Contains(".") Then
    
    
                        txtInput.Text = txtInput.Text + btnB.Text
    
                    End If
    
                Else
                    txtInput.Text = txtInput.Text + btnB.Text
                    txtInput.Text = FormatNumber(txtInput.Text, 0, TriState.True, TriState.UseDefault, TriState.UseDefault)
    
                End If
    
    
            End If
    

    The inserting of comma is already perfect, however if I tried to enter a decimal value by pressing the . button it's not working.

    Friday, May 22, 2020 2:20 PM
  • Hi lelouch_vi

    Try commenting out all your own code dealing with the TextBox text input and try putting the Sub as I posted into your code (as is) and see what the result is. Again, adjust if your TextBox is named differently.


    Regards Les, Livingston, Scotland


    • Edited by leshay Friday, May 22, 2020 2:26 PM
    Friday, May 22, 2020 2:26 PM
  • Hi lelouch_vi

    Try commenting out all your own code dealing with the TextBox text input and try putting the Sub as I posted into your code (as is) and see what the result is. Again, adjust if your TextBox is named differently.


    Regards Les, Livingston, Scotland


    Hi leshay,

    Like you said. AS IS

    but this is in the text_changed event that's why I'm not clicking any of the buttons and another one after pressing so many 9's it became 1? what is that? did it round off or something?
    • Edited by lelouch_vi Friday, May 22, 2020 2:41 PM
    Friday, May 22, 2020 2:39 PM
  • Hi

    Here is a different example to try.This one, I try to maintain User cursor position inside the TextBox if using the keyboard for entry.

    The resulting change to 1.0000 ........    is due to the FormatNumber function right enough, and I think the only way to avoid this is to write your own Formatting function (which I suppose puts you  back to square 1)

      Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        With TextBox1
          Dim s As String = .Text
          Dim sp() As String = s.Split("."c)
          Dim s2 As String = FormatNumber(sp(0), 0, TriState.True, TriState.UseDefault, TriState.UseDefault)
          Dim cp As Integer = .SelectionStart
          If s.Contains("."c) Then
            .Text = s2 & "." & sp(1)
            .SelectionStart = cp
          Else
            .Text = s2
            .SelectionStart = cp + 1
          End If
          .SelectionLength = 0
        End With
      End Sub


    Regards Les, Livingston, Scotland

    Friday, May 22, 2020 4:56 PM
  • Lelouch,

    There are 2 ways of setting thousand seperators in Arabian numbered values (used in European languages)

    The English language way by a comma (also used in Coca Cola languages where arabian numbers are used despite it is not the normal way)
    And the other European languages with a dot. 

    If I look at your name the chance is high that you use standard French. 

    By setting the language setting to UK or US or Aus (not French Can) then you get commas as thousand separator. 

    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-UK");


    Success
    Cor


    Saturday, May 23, 2020 12:09 PM
  • Hi lelouch_vi,

    In order to add commas after every 3 digit in TextBox, you can try the following code:

        Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
            TextBox1.SelectionStart = TextBox1.Text.Length
    
            If TextBox1.Text.Contains("."c) Then
    
                If TextBox1.Text.IndexOf(".") = TextBox1.Text.LastIndexOf(".") Then
                Else
                    TextBox1.Text = TextBox1.Text.Remove(TextBox1.Text.Length - 1)
                End If
            Else
                TextBox1.Text = String.Format("{0:n0}", Convert.ToDecimal(TextBox1.Text.Replace(",", "")))
            End If
        End Sub

    Result of my test:

    Hope it can help you.

    Best Regards,

    Xingyu Zhao


    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.

    • Marked as answer by lelouch_vi Thursday, May 28, 2020 4:59 AM
    Tuesday, May 26, 2020 2:35 AM
    Moderator
  • Hi lelouch_vi,

    How is the question going?  If your question has been answered then please click the "Mark as Answer" Link at the bottom of the correct post(s), so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Xingyu Zhao


    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, May 27, 2020 8:10 AM
    Moderator