Search code examples
c#validationtextbox

Allow in textbox only float (and negative float), select all, copy and paste (Ctrl+A, Ctrl+C, Ctrl+V)


Until today for validate what data I insert in the text box I used this following code:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // allows 0-9, backspace, and decimal
    if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
    {
        e.Handled = true;
        return;
    }

    // checks to make sure only 1 decimal is allowed
    if (e.KeyChar == 46)
    {
        if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
            e.Handled = true;
    }
}

It works perfectly fine, but when I try to select all, or copy or paste and also insert "-" for negative float it's just crash, how can I validate this type of "KeyPress"?


Solution

  • Try this, it should do the trick:

    private void txtFloat1_KeyPress(object sender, KeyPressEventArgs e)
            {
                // allows 0-9, backspace, and decimal
                if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46 && e.KeyChar != 45 && e.KeyChar != 3 && e.KeyChar != 22 && e.KeyChar != 1))
                {
                    e.Handled = true;
                    return;
                }
    
                // checks to make sure only 1 decimal is allowed
                if (e.KeyChar == 46)
                {
                    if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
                        e.Handled = true;
                }
            }