仅允许在文本框中浮动(和负浮动),select 全部,复制并粘贴(Ctrl+A、Ctrl+C、Ctrl+V)

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

直到今天,为了验证我在文本框中插入的数据,我使用了以下代码:

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;
    }
}

它工作得很好,但是当我尝试 select 全部,或者复制或粘贴并为负浮点数插入“-”时,它只是崩溃,我如何验证这种类型的“KeyPress”?

试试这个,它应该可以解决问题:

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;
            }
        }