我已经尝试过这段代码来限制数字。当我们尝试输入字符或任何其他控件时,它只键入数字并且不输入,即使它也没有输入退格。如何防止退格。
private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
e.Handled = true;
}
您不需要使用RegEx来测试数字:
private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar))
e.Handled = true;
}
允许退格:
private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
e.Handled = true;
}
如果要添加其他允许的键,请查看Keys
枚举并使用上述方法。
要仅允许Windows应用程序中文本框中的数字,请使用
private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
e.Handled = true;
}
此示例代码将允许输入数字和退格键以删除以前输入的文本。
使用Char.IsDigit Method (String, Int32)方法并查看Microsoft的NumericTextbox
将以下代码放在文本框的按键事件中:
private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
你可以使用Char.IsDigit()
方法
以上建议仅阻止用户输入除数字之外的任何内容,但如果用户在文本框中复制并粘贴一些文本则会失败,因此我们还需要检查文本更改事件的输入
创建ontextchangeEvent
private void TxtBox1_textChanged(object sender, EventArgs e)
{
if (!IsDigitsOnly(contactText.Text))
{
contactText.Text = string.Empty;
}
}
private bool IsDigitsOnly(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}