0

Is there any way to make thousands separator on a TextBox in visual basic? Pls tel me what are the ways are there? I say lot of thanks in advance..

matzone
  • 5,703
  • 3
  • 17
  • 20
user2613355
  • 1
  • 1
  • 1
  • This question explains very well how to do it in C#. The process is exactly the same: http://stackoverflow.com/questions/15473216/how-to-format-a-windows-forms-textbox-with-thousand-separator-and-decimal-separt – Jonathan Jul 24 '13 at 06:49
  • maskedtextbox will be easier .. http://www.dotnetheaven.com/article/maskedtextbox-control-in-vb.net1 – matzone Jul 24 '13 at 07:05
  • What sort of variable(integer, double, etc.) are you trying to show in the textbox? – dbasnett Jul 24 '13 at 11:28

2 Answers2

0

Since you're using a textbox, I would suggest also validating the users input. Here's a simple validation method that will also format the string with 2 decimal places and thousands separator:

Private Sub TextBox1_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
    Try
        TextBox1.Text = FormatNumber(TextBox1.Text, 2, TriState.False, , TriState.True)
    Catch ex As Exception
        MessageBox.Show("Only digits and/or a decimal please.")
        e.Cancel = True
    End Try
End Sub

If the string in the textbox, when it loses focus, can be parsed to a number it will be formatted. If not a messagebox notifying the user of the error is displayed and the focus returns to the textbox.

MSDN article on the validating event

MSDN article on the Try...Catch...Finally Statement

MSDN article on FormatNumber

Hard to see how one would get millions of strings input into a single line textbox, but here is another way:

Private Sub TextBox1_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
   If Double.TryParse(TextBox1.Text, vbNull) Then
       TextBox1.Text = FormatNumber(TextBox1.Text, 2, TriState.False, , TriState.True)
   Else
       MessageBox.Show("Only digits and/or a decimal please.")
       e.Cancel = True
   End If
End Sub    
tinstaafl
  • 6,908
  • 2
  • 15
  • 22
  • Use one of the TryParse methods instead of a Try-Catch. – dbasnett Jul 24 '13 at 11:31
  • 1
    If you were parsing millions of strings with a lot of 'numeric' errors you would see a huge difference. Try-Catch shouldn't be used to test the validity of whether a string can be converted to a number. It is a bad habit to use Try-Catch like this. From MSDN, "Use a Try…Catch statement only to signal the occurrence of unusual or unanticipated program events." Certainly garbage input from users is not unusual or unanticipated. – dbasnett Jul 24 '13 at 17:09
-1

The laziest way to put thousands separator on a TextBox in visual basic

  1. Right click on the TextBox .
  2. Go to properties.
  3. Search for ThousandsSeparat and set to true.

Hope it help.

enter image description here