2012-12-02 29 views
1

这是我的文本框用C#编写与键按下事件处理的Windows 8 - 文本框只接受数字出错

private void TextBox_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e) 
{ 
     //ONLY ACCEPTS NUMBERS 
     char c = Convert.ToChar(e.Key); 
     if (!c.Equals('0') && !c.Equals('1') && !c.Equals('2') && !c.Equals('3') && !c.Equals('4') && 
      !c.Equals('5') && !c.Equals('6') && !c.Equals('7') && !c.Equals('8') && !c.Equals('9')) 
     { 
      e.Handled = true; 
     } 
} 

它的作品防止字母从A到Z。但是,如果我输入符号!@#$%^ & *()_ +,它仍然接受它们。我错过了什么?

回答

1

您可以使用Char.IsDigit

e. Handled = !Char.IsDigit(c); 

但是,这不会帮助你很多在复制\粘贴的情况。

另请查看右侧的相关问题。例如Create WPF TextBox that accepts only numbers


UPDATE

对于字母只能尽量

e.Handled = Char.IsLetter(c); 
+0

仍然可以输入文本符号,而不是工作 –

+0

也忽略数字键盘:( – Sinaesthetic

+0

http://stackoverflow.com/a/30238994/1683626 –

0

没有可靠的方法来处理这个问题上按下按键或钥匙了事件,因为一些奇怪的原因移位4,是$符号返回4不是关键值。

最好的解决方法是在使用它之前捕获该值并检查它是否为数字,然后提醒用户。

var IsNumeric = new System.Text.RegularExpressions.Regex("^[0-9]*$"); 
     if (!IsNumeric.IsMatch(edtPort.Text)) 
     { 
      showMessage("Port number must be number", "Input Error"); 
      return; 
     } 

在试图教您的用户美元符号现在是一个数字的绝不是理想的,但更好!

0

试试看看这个代码。但有时你会看到你按下的字符,并立即删除。不是最好的解决方案,但足够

private void TextBox_OnTextChanged(object sender, TextChangedEventArgs e) 
{ 
    var textBox = sender as TextBox; 
    if (textBox == null) 
     return; 

    if (textBox.Text.Length == 0) return; 

    var text = textBox.Text; 

    int result; 
    var isValid = int.TryParse(text, out result); 
    if (isValid) return; 


    var selectionStart = textBox.SelectionStart; 
    var resultString = new string(text.Where(char.IsDigit).ToArray()); 
    var lengthDiff = textBox.Text.Length - resultString.Length; 

    textBox.Text = resultString; 
    textBox.SelectionStart = selectionStart - lengthDiff; 
} 
0

这可能有帮助,这是我用。

private void txtBoxBA_KeyDown(object sender, KeyRoutedEventArgs e) 
    { 
     // only allow 0-9 and "." 
     e.Handled = !((e.Key.GetHashCode() >= 48 && e.Key.GetHashCode() <= 57)); 

     // check if "." is already there in box. 
     if (e.Key.GetHashCode() == 190) 
      e.Handled = (sender as TextBox).Text.Contains("."); 
    } 
相关问题