【问题标题】:Restricting users to input only numbers in C# windows application限制用户在 C# windows 应用程序中仅输入数字
【发布时间】:2011-12-21 13:23:58
【问题描述】:

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

private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
          e.Handled = true;
}

【问题讨论】:

  • 您的意思是要允许退格吗?
  • e.Handled = "+-.\b0123456789".IndexOf(e.KeyChar)

标签: c# winforms


【解决方案1】:

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

【讨论】:

  • 如果有人在文本框中复制和粘贴文本,这将不起作用
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

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

    MSDN How to: Create a Numeric Text Box

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

          上面建议的方法只能防止用户输入除数字以外的任何内容, 但是如果用户在文本框中复制并粘贴一些文本会失败,所以我们还需要检查文本更改事件的输入

          创建 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;
              }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-03-14
            • 2019-04-12
            • 1970-01-01
            • 2023-03-17
            • 1970-01-01
            • 1970-01-01
            • 2019-10-12
            • 1970-01-01
            相关资源
            最近更新 更多