שתף באמצעות


Add Commas in Textbox as user inputs

Question

Tuesday, June 4, 2013 3:23 PM

Hi guys,

Hope you can help me

I have got a textbox in 'Microsoft visual Basic 2008 express edition', where the user inputs integer values.

As soon as the user inputs the value, I want the integer value to be formatted with commas

eg 123456 would be '123,456'

10000000 would be '100,000,00'

I attached the coding below - but it doesn't work.

Appreciate your assistance.

Thanks

Chaz

 

Private Sub textbox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textbox.TextChanged

textbox.Text = Format(textbox.test, "###,###")

End Sub

All replies (22)

Wednesday, June 5, 2013 11:41 PM ✅Answered

Please mark my post as the answer to your problem.

Your next question should really be on a new thread, but it's very simple.

Remember, all input and output must be a string.  If you need to do math calculation, the string must be converted into a number.  Make sure the string is numeric before attempting to convert.  Calculate using the numbers to get a number result.  Then convert the result into a string for output.

You need to delare a type Double variable for each of the math operands you are using in the calculation.  Convert the textbox string into one of the numbers.  Then compute with the operands and save the result to another Double variable.  Finally, convert the result to a string for output.

Note:  TryParse will convert a string to a number, but only if it is numeric.  If not, it will return 0.

For example:

Dim txtval, original, factor, result As Double
Double.TryParse(TextBox1.Text, txtval)    'converts numeric String text to type Double number 
result = txtval / original * factor     'calculates using number variables
Textbox2.Text = result.ToString()   'outputs result to a string

Be sure you place Option Strict On at the top of your code.  This will enforce correct type conversion and avoid subtle errors.

Solitaire


Tuesday, June 4, 2013 3:27 PM

Examples are at the bottom of the article

<http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx>


Tuesday, June 4, 2013 3:44 PM | 1 vote

You can use the TextChanged event to add the commas for you like this:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    If TextBox1.Text.Length = 3 Or 6 Or 9 Or 12 Or 15 Or 18 Or 21 Then
        TextBox1.Text &= ","
    End If
End Sub

Weston


Tuesday, June 4, 2013 4:00 PM

You could use either of the following.  The first one will work for both integer and double numbers.  The commented out code will work only for integers, but not with very large numbers.  The code is placed in the textbox's KeyPress event, and will execute as soon as the user presses the Enter key.

    Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress        Dim txtval As String = TextBox1.Text        Dim dblval As Double        If e.KeyChar = Chr(13) And Double.TryParse(txtval, dblval) Then            txtval = Format(dblval, "###,###")            'txtval = dblval.ToString("n")  'will include 2 decimal places            TextBox1.Text = txtval        End If        'Dim intval As Integer       'will not work for very large numbers        'If e.KeyChar = Chr(13) And Integer.TryParse(txtval, intval) Then        '    txtval = Format(intval, "###,###")        '    TextBox1.Text = txtval        'End If    End Sub

NOTE:  The code posted by another person will add commas even if the input includes non-numeric characters.  My code will ensure that the input is numeric before adding any commas.

Solitaire


Tuesday, June 4, 2013 4:03 PM

You can use the TextChanged event to add the commas for you like this:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    If TextBox1.Text.Length = 3 Or 6 Or 9 Or 12 Or 15 Or 18 Or 21 Then
        TextBox1.Text &= ","
    End If
End Sub

Weston

FYI that locks up my application.

You've taught me everything I know but not everything you know.


Tuesday, June 4, 2013 4:21 PM

Chaz1010  : Does this help ?

  Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Dim origText = Me.TextBox1.Text
        Try
            Me.TextBox1.Text = Convert.ToDecimal(Me.TextBox1.Text).ToString("N0")
            Me.TextBox1.SelectionStart = TextBox1.TextLength
        Catch ex As Exception
            Me.TextBox1.Text = origText
        End Try
    End Sub

Tuesday, June 4, 2013 4:24 PM | 1 vote

If you want the textbox to be formatted after the user is done use the validating event.

"Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it." JohnWein


Tuesday, June 4, 2013 5:05 PM

This seems to work until you have entered over, I believe it was, 29 numbers in the TextBox.

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
        If Char.IsPunctuation(e.KeyChar) Or Char.IsLetter(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        Try
            If TextBox1.Text.Length > 0 Then
                TextBox1.Text = FormatNumber(CDec(TextBox1.Text), 0)
                Dim x As Integer = TextBox1.SelectionStart
                If x = 0 Then
                    TextBox1.SelectionStart = TextBox1.Text.Length
                    TextBox1.SelectionLength = 0
                Else
                    TextBox1.SelectionStart = x
                    TextBox1.SelectionLength = 0
                End If
            End If
        Catch ex As Exception
        End Try
End Sub

You've taught me everything I know but not everything you know.


Tuesday, June 4, 2013 6:08 PM

I revised the code I posted earlier. This code does not permit input of a non-numeric character, but allows commas, since the format makes automatic corrections.  It allows the user to press the Backspace key and limits the number of digits to 28.  The remaining code is executed when the user presses the Enter key to finish the input. 

I added a LostFocus event that can be used in addition to the KeyPress event, so the code will execute even if the user does not press the Enter key but clicks on a different control.

    Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress        Dim txtval As String = TextBox1.Text        Dim decval As Decimal        If Not Char.IsDigit(e.KeyChar) Then e.Handled = True 'no non-numeric characters allowed        If e.KeyChar = Chr(8) Then e.Handled = False 'allow backspace        If e.KeyChar = "," Then e.Handled = False 'allow commas        If txtval.Length >= 28 Then            MessageBox.Show("Maximum number of digits limited to 28")            If e.KeyChar = Chr(8) Then e.Handled = False Else e.Handled = True            TextBox1.Text = txtval.Substring(0, 28)     'allow backspace to work            TextBox1.SelectionStart = TextBox1.TextLength   'cursor moved to end of text        End If        If e.KeyChar = Chr(13) Then            decval = Convert.ToDecimal(txtval)   'all text is now numeric            txtval = Format(decval, "###,###")            TextBox1.Text = txtval        End If    End Sub    Private Sub TextBox1_LostFocus(sender As Object, e As System.EventArgs) Handles TextBox1.LostFocus        Dim txtval As String = TextBox1.Text        Dim decval As Decimal        decval = Convert.ToDecimal(txtval)        txtval = Format(decval, "###,###")        TextBox1.Text = txtval    End Sub

Tuesday, June 4, 2013 7:48 PM

Hi Venkat,

Yeah it does help, but it doesn't deal with values with decimal points.

eg 12345.12 should be 12,345.12

1000000.99 should be 1,000,000.99

Thanks for your help so far - really appreciate it

Regards,

Chaz


Tuesday, June 4, 2013 7:54 PM

Hi Mr MonkeyBoy,

Yeah it does help, but it doesn't deal with values with decimal points.

eg 12345.12 should be 12,345.12

1000000.99 should be 1,000,000.99

Thanks for your help so far - really appreciate it

Regards,

Chaz


Tuesday, June 4, 2013 7:54 PM

Hi

This doesnt seem to work


Tuesday, June 4, 2013 8:12 PM

Hi Mr MonkeyBoy,

Yeah it does help, but it doesn't deal with values with decimal points.

eg 12345.12 should be 12,345.12

1000000.99 should be 1,000,000.99

Thanks for your help so far - really appreciate it

Regards,

Chaz

You never mentioned decimal points until now that I can tell. Anything else you maybe need to mention?

You've taught me everything I know but not everything you know.


Tuesday, June 4, 2013 9:12 PM

sorry my bad.

There is actually one more thing I need, but im not sure if it would be possible.

I need to add 2 shortcode for the integer value that the user inputs. 

eg

1) if user inputs 5m, it would show in the textbox as '5,000,000, 5.05m would be '5,050,000', 5.001m would be '5,001,000'

2) if user inputs 3k, it would show in the textbox as '3,000', 3.1k would be '3,100'

Thanks for your help - really do appreciate it :-)

Chaz


Tuesday, June 4, 2013 10:03 PM | 1 vote

Why do you keep changing your instructions?  You started out by saying the user was to input an integer.  Now you change it to a decimal number. 

I made some changes to my code that will allow a single decimal point to be input, and it will display the result using 2 decimal places with commas.  If no decimal point is input, it will display the result as an integer with commas.  It will not accept any other characters, such as "k" or "m" so the output should still look the way you want.

    Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress        Dim txtval As String = TextBox1.Text        Dim decval As Decimal        If Not Char.IsDigit(e.KeyChar) Then e.Handled = True 'no non-numeric characters allowed        If e.KeyChar = Chr(8) Then e.Handled = False 'allow backspace        If Not txtval.Contains(".") And e.KeyChar = "," Then e.Handled = False 'allow commas ONLY if no decimal points present        If e.KeyChar = "." And TextBox1.Text.IndexOf(".") = -1 Then e.Handled = False 'allow single decimal point        If txtval.Length >= 28 Then            MessageBox.Show("Maximum number of digits limited to 28")            If e.KeyChar = Chr(8) Then e.Handled = False Else e.Handled = True            TextBox1.Text = txtval.Substring(0, 28)     'allow backspace to work            TextBox1.SelectionStart = TextBox1.TextLength   'cursor moved to end of text        End If        If e.KeyChar = Chr(13) Then            Decimal.TryParse(txtval, decval)            If txtval.Contains(".") Then                txtval = decval.ToString("n")       'displays with 2 places after decimal point            Else                txtval = Format(decval, "###,###") 'no decimal point            End If            TextBox1.Text = txtval        End If    End Sub    Private Sub TextBox1_LostFocus(sender As Object, e As System.EventArgs) Handles TextBox1.LostFocus        Dim txtval As String = TextBox1.Text        Dim decval As Decimal        If Decimal.TryParse(txtval, decval) Then            If txtval.Contains(".") Then                txtval = decval.ToString("n")       'displays with 2 places after decimal point            Else                txtval = Format(decval, "###,###") 'no decimal point            End If        End If        TextBox1.Text = txtval    End Sub

Tuesday, June 4, 2013 10:31 PM

You need to create a dictionary and add all of your possibilities to it I believe. May take you quite some time though. But I know of no alternative. And because you never specified your full intent I believe you've had many people working towards an impossible solution for you.

Option Strict On

Public Class Form1

    Dim MyDictionary As New Dictionary(Of String, String)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Text = "Testing"
        MyDictionary.Add("1500", "15.00")
        MyDictionary.Add("5.05m", "5,050,000.00")
        MyDictionary.Add("3k", "3,000.00")
        MyDictionary.Add("3.1k", "3,100.00")
    End Sub

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        TextBox2.Text = TextBox1.Text
    End Sub

    Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
        If MyDictionary.ContainsKey(TextBox2.Text) Then
            TextBox2.Text = MyDictionary.Item(TextBox2.Text)
        End If
    End Sub

End Class

You've taught me everything I know but not everything you know.


Wednesday, June 5, 2013 10:36 PM

Hi Solitaire,

thanks for the above code, its exactly as i wanted. 

I now want to know perform a calcuation based on decimal value (saved in textbox1) on the click of a button (button 1)and output it into another textbox (textbox2).

its a simple calculation - value of textbox 1 (decimal) / value of orginal (decimal) x value of factor (decimal).

If you could assist - i would be really grateful. :-)

Thanks

Chaz


Thursday, June 6, 2013 1:26 AM

Thanks for all your help - i really appreciate it


Wednesday, June 12, 2013 12:03 PM

 Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress        Dim txtval As String = TextBox1.Text        Dim decval As Decimal        If Not Char.IsDigit(e.KeyChar) Then e.Handled = True 'no non-numeric characters allowed        If e.KeyChar = Chr(8) Then e.Handled = False 'allow backspace        If Not txtval.Contains(".") And e.KeyChar = "," Then e.Handled = False 'allow commas ONLY if no decimal points present        If e.KeyChar = "." And TextBox1.Text.IndexOf(".") = -1 Then e.Handled = False 'allow single decimal point        If txtval.Length >= 28 Then            MessageBox.Show("Maximum number of digits limited to 28")            If e.KeyChar = Chr(8) Then e.Handled = False Else e.Handled = True            TextBox1.Text = txtval.Substring(0, 28)     'allow backspace to work            TextBox1.SelectionStart = TextBox1.TextLength   'cursor moved to end of text        End If        If e.KeyChar = Chr(13) Then            Decimal.TryParse(txtval, decval)            If txtval.Contains(".") Then                txtval = decval.ToString("n")       'displays with 2 places after decimal point            Else                txtval = Format(decval, "###,###") 'no decimal point            End If            TextBox1.Text = txtval        End If    End Sub    Private Sub TextBox1_LostFocus(sender As Object, e As System.EventArgs) Handles TextBox1.LostFocus        Dim txtval As String = TextBox1.Text        Dim decval As Decimal        If Decimal.TryParse(txtval, decval) Then            If txtval.Contains(".") Then                txtval = decval.ToString("n")       'displays with 2 places after decimal point            Else                txtval = Format(decval, "###,###") 'no decimal point            End If        End If        TextBox1.Text = txtval    End Sub

Hi Solitaire,

Hope you are well.

Would you be able to modify the below code to accept characters? Thanks for your help


Wednesday, June 12, 2013 1:54 PM

Easly remove the comma doing:

TextBox1.Text.Replace("," , "")

?


Wednesday, June 12, 2013 2:08 PM

What happens if the user pastes a value into the TextBox?  These sort of decorations create more problems than they are worth, IMHO, and tend to be a maintenance nightmare.

"Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it." JohnWein

Multics


Wednesday, June 12, 2013 3:36 PM

 Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        Dim txtval As String = TextBox1.Text
        Dim decval As Decimal
        If Not Char.IsDigit(e.KeyChar) Then e.Handled = True 'no non-numeric characters allowed
        If e.KeyChar = Chr(8) Then e.Handled = False 'allow backspace
        If Not txtval.Contains(".") And e.KeyChar = "," Then e.Handled = False 'allow commas ONLY if no decimal points present
        If e.KeyChar = "." And TextBox1.Text.IndexOf(".") = -1 Then e.Handled = False 'allow single decimal point
        If txtval.Length >= 28 Then
            MessageBox.Show("Maximum number of digits limited to 28")
            If e.KeyChar = Chr(8) Then e.Handled = False Else e.Handled = True
            TextBox1.Text = txtval.Substring(0, 28)     'allow backspace to work
            TextBox1.SelectionStart = TextBox1.TextLength   'cursor moved to end of text
        End If
        If e.KeyChar = Chr(13) Then
            Decimal.TryParse(txtval, decval)
            If txtval.Contains(".") Then
                txtval = decval.ToString("n")       'displays with 2 places after decimal point
            Else
                txtval = Format(decval, "###,###") 'no decimal point
            End If
            TextBox1.Text = txtval
        End If
    End Sub
    Private Sub TextBox1_LostFocus(sender As Object, e As System.EventArgs) Handles TextBox1.LostFocus
        Dim txtval As String = TextBox1.Text
        Dim decval As Decimal
        If Decimal.TryParse(txtval, decval) Then
            If txtval.Contains(".") Then
                txtval = decval.ToString("n")       'displays with 2 places after decimal point
            Else
                txtval = Format(decval, "###,###") 'no decimal point
            End If
        End If
        TextBox1.Text = txtval
    End Sub

Hi Solitaire,

Hope you are well.

Would you be able to modify the below code to accept characters? Thanks for your help

Wow. Forums needs a new forum "Do my code for me in VB.Net"

You've taught me everything I know but not everything you know.