How to limit a text box to numbers only and a single decimal point during the key press event?

advertisements

This question already has an answer here:

  • How to make a textBox accept only Numbers and just one decimal point in Windows 8 13 answers

Here is my current code it only accepts numbers, what should I add to allow one decimal point?

 private void txtPurchasePrice_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (!char.IsNumber(e.KeyChar))
                {
                    e.Handled = true;
                }


Here's what worked for me!

  private void txtPurchasePrice_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
        (e.KeyChar != '.'))
    {
            e.Handled = true;
    }

    // only allow one decimal point
    if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
    {
        e.Handled = true;
    }
}