如何在Win Form文本框中添加掩码,以便仅允许数字?并且它如何适用于其他掩码数据,例如电话号码、邮政编码等。
我正在使用Visual Studio 2008 C#。
谢谢。
您想要防止不允许的输入或在继续之前验证输入吗?
前者可能会使用户按键时感到困惑,但什么也不会发生。通常最好显示他们的按键,但显示输入当前无效的警告。例如,对于遮蔽电子邮件地址正则表达式,设置可能也相当复杂。
请查看ErrorProvider,以允许用户键入所需内容,但在键入时显示警告。
对于您的第一个建议,即仅允许数字的文本框,您还可以考虑使用NumericUpDown。
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;
}
}
为了只允许电话号码的值:
private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9') return;
if (e.KeyChar == '+' || e.KeyChar == '-') return;
if (e.KeyChar == 8) return;
e.Handled = true;
}