Share via


How to add comma in 1000, 100000 in vb.net?

Question

Monday, March 26, 2012 7:40 PM

Hi~! I always have this problem. I have a textbox but is disabled and you can only input through a button. So, I want the input number "1000" to be like this, "1,000" but I don't know what code to put. Same thing with 100000 = 100,000. Can anyone help me? 

All replies (26)

Thursday, March 29, 2012 12:45 AM ✅Answered | 1 vote

You can add an error handler so if the user input more than 5000 or what ever the program will through a msg.

Public Class Form1    'This will make the Button Text Properties used to input the numbers    Private Sub buttons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click, Button8.Click, Button9.Click, Button10.Click        Dim btn As Button = CType(sender, Button)        TextBox1.Text &= btn.Text        Dim val As Integer        val = TextBox1.Text        If val > 999 Then            TextBox1.Text = val.ToString("###,###")        End If        If val > 5000 Then            MsgBox("You are not allowed to withdrawal more than 5,000  Peso.", MsgBoxStyle.Information, "Error!")        End If    End SubEnd Class


Monday, March 26, 2012 8:25 PM | 3 votes

You can format the string when you add the number:

     Dim num as Integer = 1000

     textBox1.Text = num.ToString("N")

For details, see the available format strings here: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".


Tuesday, March 27, 2012 3:03 AM

Hi! The code was working but if you press button1 and has a number "1", the only thing that will appear is 1,000.00 and you can never press  anything. What I also mean is that, whenever my digit becomes 4, it will automatically put a comma in between the index 0 and 1, same like 1,000.


Tuesday, March 27, 2012 6:29 AM

Hi joevalle90,

I am moving your thread into the Visual Basic General Forum for dedicated support. Thanks for your understanding.

Best Regards

Jack Zhai [MSFT]
MSDN Community Support | Feedback to us


Tuesday, March 27, 2012 6:41 AM

you can specify the format of the string in the ToString method

Dim strNumber As Double = 10000000.5
    
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox1.Text = strNumber.ToString("#,#.#")
    End Sub

“This forum post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.”


Tuesday, March 27, 2012 7:00 AM

Joe,

A textbox is not the best choise for what you want. Be aware numbers are inserted in all kind of formats in the world depending of the culture. 

In most languages the comma is a decimal seperator while in the English language culture (except that part in South Africa) the point is a comma seperator. 

Therefore if it should be like you wrote then take the masked textbox.

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

Success
Cor


Tuesday, March 27, 2012 7:17 AM

Try this:

Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
    TextBox1.Text = CDbl(TextBox1.Text).ToString("N")
    TextBox1.SelectionStart = TextBox1.Text.IndexOf(".")
End Sub

From my understanding you wanted it to input them automatically as you type, so i'm assuming the handler of the TextChanged event in a TextBox. It's not perfect... But it works as some psuedo code if you're persistent on having a TextBox control here. You may want to use a MaskedTextbox in combination with this to avoid invalid input which could raise exceptions/errors. And if you need to edit that decimal, then you may want to check the position of the ibeam with the SelectionStart property for that TextBox control to see where it is inside of the existing text number value.

Cheers :)

If a post helps you in any way or solves your particular issue, please remember to use the Propose As Answer option or Vote As Helpful
~ "The universe is an intelligence test." - Timothy Leary ~


Tuesday, March 27, 2012 1:18 PM

I generally format a textbox on leaving,

   '##  FORMAT TEXT AS DBL ON LEAVING DISCOUNT AMOUNT
    Private Sub txtBillingDiscount_Leave(sender As Object, e As System.EventArgs) Handles txtBillingDiscount.Leave
        If IsNumeric(txtBillingDiscount.Text) Then
            txtBillingDiscount.Text = Format(CDbl(txtBillingDiscount.Text), "#0.00")
        End If
    End Sub

The generic format for what you want would be

Format(Cint(Textbox1.text), "#,##0")

US Currency would be "$#,##0.00", & etc where 0 represents a default and # represents any number

Dan


Tuesday, March 27, 2012 2:51 PM

Hi Everyone!
I really appreciate your help but sad to say none of them work.

ACEINFINITY's code output whenever I click Button1 with a value of 1 is like this:
"1.00" and whenever I click other button with value from 1 to 9, it will just add 1 to the right index, it will become like this 1.01... keeps on pressing the button, it will just add 0.01 to the textbox. You have to press a hundred times to make it 2.00;

JWAVILA's code is not the right one because the number should not be declared in dim, like this.

Dim strNumber as Double = 100000.5

The comma should depend on the number of digits inputted in the textbox. You don't need to set a specific value to let the comma come out. If I enter 3 digit comma wont show but if I add 1 digit to make it 4, the comma will automatically show, something like that.


Tuesday, March 27, 2012 4:01 PM

I'm not sure what you want since you have several typos.  Like the following?

    Private Function xFormat(ByVal num As Decimal) As String
        Dim myNum As String = ""
        myNum = String.Format("{0:" + "#,##0}", num)
        Return myNum
    End Function
    '
    '
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Dim n As Integer = CInt(TextBox1.Text)
            TextBox2.Text = xFormat(n)
        Catch ex As Exception
        End Try
    End Sub

Onion is a recent refuge from Mac OS X and hates Mac App Store. System: Windows 7 x64


Tuesday, March 27, 2012 8:02 PM

The very first reply is the answer.

You never show your code so we have no idea what buttons you have or what they are supposed to do - and anyway, it isn't relevant...

Somewhere you have a numeric variable and somewhere in your code you set  TextBox.Text = numericVariable

When you do, add .ToString("N") to whatever your numeric variable is and set the textbox's text to that.

OutputTextBox.Text = numericVariable.ToString("N")

Note that you can also use "N0" for zero decimal places, or "N2" for two decimal places, etc.  The commas will be handled automatically according to the default culture's number format info.

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


Tuesday, March 27, 2012 10:44 PM

Hi Everyone!
I really appreciate your help but sad to say none of them work.

Strange I see you tell a lot around the textbox but nothing about the masked textbox.

Be aware if you had asked how can I fly with a submarine the answer would also have been try a plane instead of a submarine.

And now you tell that none of them work; that is true, a submarine cannot fly no matter how many times you tell it must.

Success
Cor


Wednesday, March 28, 2012 3:18 AM

Hi joevalle90,

Try this code:

Public Class Form1    ' In this code we added the input numbers of     ' TextBox1.Text and TextBox2.Text and show it    ' in TextBox3.Text    ' Just add three text boxes and a button to    ' your form.    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click        Dim num1 As Integer = TextBox1.Text        Dim num2 As Integer = TextBox2.Text        Dim result As Integer = CInt(num1 + num2)        TextBox3.Text = result.ToString("###,###")    End SubEnd Class

Regards,


Wednesday, March 28, 2012 2:29 PM

I'm sorry for too much talking without showing any code. My mistake.
Here is my code for button1, the output will be in a textbox named "txtWith":

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        If btnRemove1.Enabled = True Then
            txtWith.Text = txtWith.Text & "1"
        Else
            MsgBox("You are not allowed to input number.", MsgBoxStyle.Information, "Error!")
        End If

    End Sub

         


Wednesday, March 28, 2012 2:36 PM

Then I assume you are trying to this:

Public Class Form1
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        txtPin.Text = "1"
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If btnRemove1.Enabled = True Then
            txtPin.Text = CInt(txtPin.Text & "1").ToString("N0")
        Else
            MsgBox("You are not allowed to input number.", MsgBoxStyle.Information, "Error!")
        End If
    End Sub
End Class

However, you would only be able add nine more 1s before you hit an overflow.

Are you trying to work with an actual "Number" or do you just need a string of 1s with commas which can be any length?  It might be easier if you could explain the purpose of the code (that is, tell us the ultimate goal you are trying to accomplish).

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


Wednesday, March 28, 2012 4:03 PM

Then I assume you are trying to this:

Public Class Form1
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        txtPin.Text = "1"
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If btnRemove1.Enabled = True Then
            txtPin.Text = CInt(txtPin.Text & "1").ToString("N0")
        Else
            MsgBox("You are not allowed to input number.", MsgBoxStyle.Information, "Error!")
        End If
    End Sub
End Class

However, you would only be able add nine more 1s before you hit an overflow.

Are you trying to work with an actual "Number" or do you just need a string of 1s with commas which can be any length?  It might be easier if you could explain the purpose of the code (that is, tell us the ultimate goal you are trying to accomplish).

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

I'm actually making a System for my final exam and specifically this is a Banking System. So, I'll dealing more with numbers. The code that I am asking is for the ATM GUI. Are you familiar with withdrawal? So, if you want to get cash in your account via atm, you will be prompt/show you a textbox to enter the desired amount you want to get and if it reached a four digit, it will automaticall add a comma, right? But I've seen an atm machine that doesn't add comma. I've been to atm awhile ago and noticed that the textbox for the withdrawal doesn't add comma, but some automatically add comma.

The adding of comma in cash is a plus for our system, else, this will subtract some points if this system will be checked.


Wednesday, March 28, 2012 4:14 PM

I've never seen an ATM that allowed more than a $300 withdrawl... I've never seen one that went up to or beyond $1000.00 so I'm not sure when you would ever see the comma...

At any rate, do you have 10 buttons then like a calculator?  The digits 0-9 each on their own button?

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


Wednesday, March 28, 2012 4:47 PM

Yes Reed, it's like a calculator wherein you need to press a button so that the screen will have input. Uhhm, I don't know in your country because in our country you can get 5,000.00 but not in dollar, rather in Peso.


Wednesday, March 28, 2012 6:30 PM

I put a Panel and a Label on a form. I store the number entered separately from the display of that number. To append a digit, I multiply the number by 10 and add the input number.

Public Class Form1

    Dim someNumber As Integer = 0

    Sub bnPress(sender As Object, e As EventArgs)
        Dim bn = CType(sender, Button)
        Dim n = CInt(bn.Text)
        someNumber = someNumber * 10 + n
        Label1.Text = someNumber.ToString("N0")

    End Sub

    Sub CreateNumberButtons()
        Dim bn As Button
        Dim value As Integer

        Panel1.SuspendLayout()
        Panel1.Location = New Point(20, 20)
        Panel1.Size = New Size(40 * 3, 40 * 4)

        ' messy bits, but it's only for testing
        For i = 0 To 9
            value = (i + 1) Mod 10
            bn = New Button With {.Text = value.ToString, _
                                .Location = New Point(((i Mod 3) + If(i = 9, 1, 0)) * 40 + 4, (i \ 3) * 40 + 4), _
                                .Size = New Size(30, 30)}
            AddHandler bn.Click, AddressOf bnPress
            Panel1.Controls.Add(bn)
        Next

        Panel1.ResumeLayout()

        ' stick the label below the panel
        Label1.Location = New Point(20, Panel1.Bottom + Label1.Height)

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CreateNumberButtons()
    End Sub

End Class

It was simpler (for me) than figuring out the mask for a maskedtextbox.

I leave it to you to right-justify the display of the number and to implement delete and clear functions.

HTH,

Andrew


Wednesday, March 28, 2012 11:25 PM

On the off chance that you want to do this manually...

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim Number As Integer = 1000032420
        MsgBox(CSTRComma(Number))
    End Sub
    Public Function CSTRComma(ByVal N As Integer) As String
        Dim S As String = N.ToString
        Dim A As String = ""
        For I = Len(S) To 1 Step -1
            A = Mid(S, I, 1) & A
            If I Mod 3 = 2 Then
                A = Chr(44).ToString & A
            End If
        Next
        Return A
    End Function

If you want something you've never had, you need to do something you've never done. If you believe something to be true, then one day you will be called upon to demonstrate that truth.


Thursday, March 29, 2012 12:12 AM

Joevalle90,

Check this code. It will add the comma for evry three digits. Add 10 buttons, Button1 text is 1 Button2 text is 2 ..Button10 text is 0

Public Class Form1    'This will make the Button Text Properties used to input the numbers    Private Sub buttons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click, Button8.Click, Button9.Click, Button10.Click        Dim btn As Button = CType(sender, Button)        TextBox1.Text &= btn.Text        Dim val As Integer        val = TextBox1.Text        If val > 999 Then            TextBox1.Text = val.ToString("###,###")        End If    End SubEnd Class


Thursday, March 29, 2012 1:10 AM

One more thing, You can clear the textbox if the input is more than the max using:

TextBox1.Clear() 'just under the MsgBox line.


Thursday, March 29, 2012 8:33 AM

>>txtWith.Text = txtWith.Text & "1"

This line of code is where my code doesn't work for you because it formats in decimal, but that doesn't quite mean that my method did not work, it did what you wanted, but now you're trying to apply this output to a button click event. In which case would be that the button click event needs to be modified.

You could invest some time into the Insert() method to insert at the index before the "." in the formatted value in the textbox for the button click event to insert a number.

My code was proposed to you also as a text_changed event snippet, not a button click event, so I didn't have an idea that you were using buttons. For this system though are you allowing for decimal input or no?

More clarification on that would help.

Cheers
~Ace

If a post helps you in any way or solves your particular issue, please remember to use the Propose As Answer option or Vote As Helpful
~ "The universe is an intelligence test." - Timothy Leary ~


Thursday, March 29, 2012 5:45 PM

You can add an error handler so if the user input more than 5000 or what ever the program will through a msg.

Public Class Form1
    'This will make the Button Text Properties used to input the numbers
    Private Sub buttons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click, Button4.Click, Button5.Click, Button6.Click, Button7.Click, Button8.Click, Button9.Click, Button10.Click
        Dim btn As Button = CType(sender, Button)
        TextBox1.Text &= btn.Text
        Dim val As Integer
        val = TextBox1.Text
        If val > 999 Then
            TextBox1.Text = val.ToString("###,###")
        End If
        If val > 5000 Then
            MsgBox("You are not allowed to withdrawal more than 5,000  Peso.", MsgBoxStyle.Information, "Error!")
        End If
    End Sub
End Class

Thank you guys! I really appreciate all your effort for answering my question. Especially to SalleMander, so thankful! My problem is now solved! I will also keep this code  for future use. I'd also like to thank Reed Kimble for spending a bit of his time answering my question and to Sallemander for giving me the right answer. MSDN Rock! :)


Thursday, March 29, 2012 11:12 PM

Keep in mind with SalleMander's code, you're implicitly converting your types, if this is a homework project, you should try to avoid that for properness. Glad you got it figured out. :)

If a post helps you in any way or solves your particular issue, please remember to use the Propose As Answer option or Vote As Helpful
~ "The universe is an intelligence test." - Timothy Leary ~


Tuesday, October 25, 2016 7:26 AM

worked , thanks so much