Restrict Characters Allowed In TextBox(Entering Money Amount)

cb1295 picture cb1295 · Sep 4, 2011 · Viewed 16.9k times · Source

So I have a Subtotal TextBox where an amount like $546.75 can be entered. Now, I want to make sure that only numbers, ONE decimal, One Dollar Symbol and commas allowed only every 3 places (100,000,000). Is this possible? Maybe not the commas, but at least the numbers, decimal, and dollar symbol.

Answer

Mitja Bonca picture Mitja Bonca · Sep 4, 2011

Why you dont put the money sign "$" out side of the textBox (create a label just infrontof textBox), then you will not have to worry about this character, but only about numbers. And it looks better (in my opinion). Then you can use this code:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar != (Char)Keys.Back) //allow backspace (to delete)
        {
            e.Handled = !char.IsNumber(e.KeyChar);
        }
    }