[英]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"?它工作得很好,但是当我尝试 select 全部,或者复制或粘贴并插入“-”作为负浮点数时,它只是崩溃,我如何验证这种类型的“KeyPress”?
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.