只有“ - ”的文本框数字

时间:2013-12-06 10:03:32

标签: textbox

我有这段代码,但我希望能够使用负数,但是使用此代码我不能使用“ - ” 我查看了密钥枚举,但我无法在该页面上找到它。

    private void tbInvoerEuros1_KeyPress(object sender, KeyPressEventArgs e) 
    {
        char ch = e.KeyChar;


        if e.Handled = !(Char.IsDigit(ch) || (ch == '-') || (ch < ' ') && ch != 46 && ch != 8));
        {
            e.Handled = true;
        }
    }

1 个答案:

答案 0 :(得分:1)

最简单的解决方案(基于您的代码)可能看起来像这样:

private void tbInvoerEuros1_KeyPress(object sender, KeyPressEventArgs e) {
  char ch = e.KeyChar;

  // Stop processing character unless it 
  //   - digit
  //   - minus sign
  //   - command character (e.g. BackSpace, Enter, Escape)
  // (ch < ' ') better than (ch != 8) because you'd probably want to 
  // preserve commands like ENTER (13), ESCAPE (27), SHIFT TAB (15) etc.
  e.Handled = !(Char.IsDigit(ch) || (ch == '-') || (ch < ' '));
}

但你可能不得不考虑一些问题:

  1. 用户可以在文本框中粘贴文字,因此您必须使用TextChanged事件
  2. 减号似乎是一个特殊的符号:如果,例如,用户输入“1”,“2”,“ - ”你可能应该把它写成“-12”,而不是“12 - ”