更新时间:2022-12-22 14:42:34
private void txtPrinterNumber_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;
}
}
它可以完成 - 它并不复杂,只是烦人,因为你必须处理它防止粘贴添加alpha的地方。
更好的解决方案是使用NumericUpDown控件,它可以为你完成所有。
如果您打算手动执行此操作,请考虑查看TextChanged事件并使用Regex.Replace而不是IsMatch - 但不要忘记光标位置可能需要更正。
It can be done - it's not complex, it's just annoying, because you have to handle it in a number of places to prevent paste adding alpha as well.
The better solution is to use a NumericUpDown control, which does it all for you.
If you are going to do it manually, consider looking at the TextChanged event and using Regex.Replace instead of IsMatch - but don't forget the cursor position may need correcting.