How to force textbox to take only numbers in WPF?

38,849

Solution 1

protected override void OnPreviewTextInput(TextCompositionEventArgs e)
    {
        char c = Convert.ToChar(e.Text);
        if (Char.IsNumber(c))
            e.Handled = false;
        else
            e.Handled = true;

        base.OnPreviewTextInput(e);
    }

Solution 2

You can use a validation rule... http://www.codeproject.com/KB/WPF/wpfvalidation.aspx

Or make your own Maskable textbox http://rubenhak.com/?p=8

Solution 3

//Call this code on KeyDown Event
if((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || (e.Key == Key.Back))
{ e.Handled = false; }
else if((e.Key >= Key.D0 && e.Key <= Key.D9))
{ e.Handled = false; }
else
{ e.Handled = true; }

Solution 4

You can bind your textbox with a dependency property and inside dependency property's validation method you can check if int.tryparse returns true then fine otherwise you can go for default or you can reset value.

Or you can use WPF ValidationRules to find out when the value is changed. Once changed you can apply logic for inout validaiton.

Or you can use IDataError Info for validation.

Solution 5

bit enhanced version of Hasib Uz Zaman

     private void txtExpecedProfit_PreviewTextInput_1(object sender, TextCompositionEventArgs e)
    {
        CheckIsNumeric((TextBox)sender,e);
    }

    private void CheckIsNumeric(TextBox sender,TextCompositionEventArgs e)
    {
        decimal result;
        bool dot = sender.Text.IndexOf(".") < 0 && e.Text.Equals(".") && sender.Text.Length>0;
        if (!(Decimal.TryParse(e.Text, out result ) || dot )  )
        {
            e.Handled = true;
        }
    }

this will check for duplication .(decimal mark) and will not allow just only .(decimal mark)

Share:
38,849

Related videos on Youtube

Hasib Uz Zaman
Author by

Hasib Uz Zaman

Software Developer

Updated on July 09, 2022

Comments

  • Hasib Uz Zaman
    Hasib Uz Zaman almost 2 years

    I want user to enter only numeric values in TextBox.

    I got this code:

    private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
    {
         int isNumber = 0;
         e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);
    }
    

    But I am not getting textbox_KeyPress event and e.KeyChar while using WPF.

    Whats the solution in WPF?

    Edit:

    I made a Solution!

    private void txtName_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        CheckIsNumeric(e);
    }
    
    private void CheckIsNumeric(TextCompositionEventArgs e)
    {
        int result;
    
        if(!(int.TryParse(e.Text, out result) || e.Text == "."))
        {
            e.Handled = true;
        }
    }
    
    • Falcon
      Falcon almost 9 years
      Got It Was Really Help full.. It worked....
    • Pinotek
      Pinotek over 7 years
      View here You can find here a good overview of answers for it.
  • Anna Lam
    Anna Lam almost 12 years
    Good answer! Although, I would replace all but the last line of your method body with e.Handled = !Char.IsNumber(Convert.ToChar(e.Text));
  • Igor
    Igor over 10 years
    PreviewTextInput() will not catch the 'space' key press. Adding if (e.Key == Key.Space) e.Handled = true; in the PreviewKeyDown() would solve that problem.
  • dcp
    dcp over 8 years
    This answer doesn't solve problem of user pasting a value into the textbox. The pasted value could contain letters.
  • Dragos Stoica
    Dragos Stoica about 8 years
    not working in conjunction to Shift. You can insert special characters
  • סטנלי גרונן
    סטנלי גרונן about 7 years
    Better if you could add some explanation, dome details, not code only. The idea is that other users could also benefit from your answer as well (in the future), not only the OP. Just a thought :)