限制用户仅在C#windows应用程序中输入数字

问题描述 投票:8回答:6

我已经尝试过这段代码来限制数字。当我们尝试输入字符或任何其他控件时,它只键入数字并且不输入,即使它也没有输入退格。如何防止退格。

private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
          e.Handled = true;
}
c# winforms
6个回答
27
投票

您不需要使用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枚举并使用上述方法。


8
投票

要仅允许Windows应用程序中文本框中的数字,请使用

private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
          e.Handled = true;
}

此示例代码将允许输入数字和退格键以删除以前输入的文本。


6
投票

使用Char.IsDigit Method (String, Int32)方法并查看Microsoft的NumericTextbox

MSDN How to: Create a Numeric Text Box


5
投票

将以下代码放在文本框的按键事件中:

     private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
    }

3
投票

你可以使用Char.IsDigit()方法


0
投票

以上建议仅阻止用户输入除数字之外的任何内容,但如果用户在文本框中复制并粘贴一些文本则会失败,因此我们还需要检查文本更改事件的输入

创建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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.