4

I want a user to only write numbers (0-9) in a TextBox. I'm using following code to prevent the user of writing letters and other characters except of numbers, but I can't avoid the user to use the space in the TextBox.

private void CheckIsNumeric(TextCompositionEventArgs e)
{
    int result;

    if (!(int.TryParse(e.Text, out result)))
    {
       e.Handled = true;
       MessageBox.Show("!!!no content!!!", "Error", 
                       MessageBoxButton.OK, MessageBoxImage.Exclamation);
    }
}

I allready tried using something like

if (Keyboard.IsKeyDown(Key.Space))
{ //...}

but did not succeed.

Thanks for help.

Morris
  • 159
  • 1
  • 2
  • 10
  • I tried that as well and it allows space as well. – Morris Aug 02 '17 at 09:56
  • a comment on accepted answer in the duplicate question addresses and supports that problem: "[Space] doesn't fire PreviewTextInput event". From which event do you call your `CheckIsNumeric` method? – Cee McSharpface Aug 02 '17 at 10:34
  • 1
    Oh sorry, I must have overlooked that. I'm using a PreviewTextInput event to that will be the problem. I bypassed my problem with textbox.Text.Replace(" ","") . So now all spaces are removed afterwards whats good enough for me. – Morris Aug 02 '17 at 10:55
  • If you've bound the Text property of the TextBox to a property in your view model, you can just have the setter of the property do: set { _foo = value.Replace(" ", ""); } – Iain Holder Sep 10 '18 at 11:14
  • And I don't know why this question was closed as a duplicate. It's related to the questions cited but it's very specific and should have been left. – Iain Holder Sep 10 '18 at 11:14

2 Answers2

0

Check for spaces seperate, or just correct spaces, before check. So user can space-ing as much as want and that do not change anything.

private void CheckIsNumeric(TextCompositionEventArgs e)
{
    int result;
  string removedSpaces =  e.Text.Replace(" ","");
    if (!(int.TryParse(removedSpaces, out result)))
    {
       e.Handled = true;
       MessageBox.Show("!!!no content!!!", "Error", 
                       MessageBoxButton.OK, MessageBoxImage.Exclamation);
    }
}
raichiks
  • 286
  • 4
  • 16
  • 1
    Thanks for your answer, but this does not change anything. As I have been told a PreviewTextInput event does not react to space, so I will need a total different approach. – Morris Aug 02 '17 at 10:58
  • The only way we can restrict is using KeyDown event e.Handled=e.Key==Key.Space. – Sunny Apr 12 '21 at 11:49
0

register KeyPress event for Your textBox and add this code.

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

    // If you want to allow decimal numeric value in you textBox then add this too 
    if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
    {
        e.Handled = true;
    }
}
Blue
  • 312
  • 2
  • 12