Alex Felton-Smith
Alex Felton-Smith

Reputation: 27

Display commas in textbox VB.net

I have a textbox that gets a value from a calculation. I'm trying to get it to display commas when the value is over 999.99 I've tried Convert.ToDecimal and Convert.ToString but it doesn't seem to work. Here is the code that populates the field. Any help would be greatly appreciated.

IskMade1.Text = Convert.ToDecimal(IPU1.Text) * Convert.ToDecimal(Units1.Text)

The IskMade1 field displays the decimal correctly, but it isn't adding any commas to the number.

Upvotes: 0

Views: 7733

Answers (2)

user1593881
user1593881

Reputation:

Provided you have some MyDecimalVariable variable in which you store the decimal values you could format the TextBox text as follows:

Dim MyDecimalVariable As Decimal = 1234.56
IskMade1.Text = MyDecimalVariable.ToString("#,##0.00")

or you could have:

Dim MyDecimalVariable As Decimal = 1234.56
IskMade1.Text = MyDecimalVariable.ToString("N", CultureInfo.InvariantCulture)

in which case you would need to import the System.Globalization namespace.

Upvotes: 4

Blackwood
Blackwood

Reputation: 4534

If IPU1 and Units1 are TextBoxes, you should check that the Text property can be converted to a number before doing the conversion. Decimal.TryParse can do that for you. Then use ToString("N") to convert to a string with comma separators, or ToString("N2") if you want to show two decimal places.

Dim ipuNum, units as Decimal
If Decimal.TryParse(IPU1.Text, ipuNum) AndAlso Decimal.TryParse(Units1.Text) Then
    IskMade1.Text = (ipuNum * units).ToString("N")
Else
    'Error processing goes here
End If

What you do for error processing is up to you. You could use MessageBox.Show to display an error message and (if this is a Button Click handler) Exit Sub

Upvotes: 0

Related Questions