1

here is my TextBox written in C# with Key Down event handler

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

it does works preventing letters from a to z. However, if I enter symbols like !@#$%^&*()_+, it stills accept them. What am I missing?

Hendra Anggrian
  • 5,780
  • 13
  • 57
  • 97

4 Answers4

1

You can use Char.IsDigit

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

But this won't help you much in case of copy\pasting.

Also check related question on the right. For example Create WPF TextBox that accepts only numbers


UPDATE

For letters only try

e.Handled = Char.IsLetter(c);
Community
  • 1
  • 1
Dev
  • 367
  • 1
  • 10
0

There is no reliable way to handle this on the key down or key up events because for some odd reason shift 4 which is the $ sign returns 4 not the key value.

The best workaround is to catch the value before it's used and check it is numeric then alert the user.

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

In no way ideal but better that trying to teach your users that the dollar sign is now a number!

depicus
  • 301
  • 4
  • 19
0

Try this code. But sometimes you see char that you pressed and it is removed immediately. Not the best solution but sufficient

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;
}
y0j0
  • 3,369
  • 5
  • 31
  • 52
0

this might help, this is what I used.

    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(".");
    }
Rohit
  • 1,520
  • 2
  • 17
  • 36