【发布时间】:2021-08-11 15:54:33
【问题描述】:
我正在尝试制作一个只接受数字的文本框。
private void depositTextBox_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;
}
}
这是在设计器中。
this.depositTextBox.KeyPress += new System.EventHandler(this.depositTextBox_KeyPress);
其他错误。
No overload for 'depositTextBox_KeyPress' matches delegate 'EventHandler'
【问题讨论】:
-
小数点分隔符不是点怎么办?如果键入多个分隔符怎么办?如果只输入符号而无法解析有效数字怎么办?如果通过热键/Windows 消息/上下文菜单粘贴了某些内容怎么办?我看到的所有纯数字文本框都存在缺陷且笨拙。相反,使用验证。更简单也更清洁。或者简单地将
TextBox绑定到 int/float/decimal 属性或DataTable列,一切都会按预期工作。
标签: c# winforms textbox event-handling keypress