WPF TextBox not allowed

I want the user to only write numbers (0-9) in the TextBox. I am using the following code to prevent the user from writing letters and characters other than numbers, but I cannot avoid the user using 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 have already tried using something like

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

      

but failed.

Thanks for the help.

+3


source to share


2 answers


Check for spaces separately before checking, or just fix the spaces. This way the user can take up as much space as he wants and doesn't 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);
    }
}

      

0


source


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

      

0


source







All Articles