Format Textbox for $$$

 

I would like to know how can i set my textbox up so that when i enter 1600 it turns it into 16.00

I thought this would work but i was wrong

txtValue.Text =  Format(#,##0.00)




Answer this question

Format Textbox for $$$

  • svashchenko

    you may have to consider some additional error checking but this should get you on the right track:

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

    If Char.IsNumber(e.KeyChar) Then

    e.Handled = True

    Select Case TextBox1.Text.Length

    Case Is = 0

    TextBox1.Text = "0.0" & e.KeyChar

    Case Is >= 1

    TextBox1.Text = TextBox1.Text.Trim("0")

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

    TextBox1.Text = TextBox1.Text & e.KeyChar

    TextBox1.Text = TextBox1.Text.Insert(TextBox1.Text.Length - 2, ".")

    End Select

    Else

    e.Handled = True

    End If

    End Sub



  • LeRainieur

    From the sample provided, I would use the following:

    txtValue.Text = myDecimal/100.ToString("n2")

    I typically find my users are used to pressing the period key so I would not worry about the /100 part. You would want to check to make sure they enter a valid number however.

    You could format it as currency instead of a number if you want by using myDecimal.ToString("c2"). Watch out for the default behavior of Decimal.TryParse with currency values, though. (see http://devauthority.com/blogs/jwooley/archive/2006/03/15/788.aspx)

    Jim Wooley



  • Saberinth

    You could just use the MaskedTextBox, then you wouldn't have to write any code. Just simply set the Mask property to the format you want and voila, no nasty parsing code.
  • Edward Clements

    Another thought, are you trying to format a number or the entered value in the text box (which is a string) You need to convert the string to a number before you can use the Format(#,##0.00) or .ToString("n2") methods. It won't work if you are just trying to format a string as another string.

    Jim Wooley
    http://devauthority.com/blogs/jwooley



  • Format Textbox for $$$