27

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;
    }
}
Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
Hasib Uz Zaman
  • 297
  • 1
  • 3
  • 8
  • Got It Was Really Help full.. It worked.... – Falcon Jun 05 '15 at 06:17
  • [View here](http://stackoverflow.com/questions/1268552/how-do-i-get-a-textbox-to-only-accept-numeric-input-in-wpf) You can find here a good overview of answers for it. – Pinotek Oct 17 '16 at 10:17

8 Answers8

18
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);
    }
Niki Nikpour
  • 211
  • 2
  • 4
  • 4
    Good answer! Although, I would replace all but the last line of your method body with e.Handled = !Char.IsNumber(Convert.ToChar(e.Text)); – Anna Lam Jul 06 '12 at 05:30
  • 10
    `PreviewTextInput()` will not catch the 'space' key press. Adding `if (e.Key == Key.Space) e.Handled = true;` in the `PreviewKeyDown()` would solve that problem. – Igor Oct 13 '13 at 16:29
  • 2
    This answer doesn't solve problem of user pasting a value into the textbox. The pasted value could contain letters. – dcp Feb 02 '16 at 19:19
8

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

Phil Murray
  • 6,396
  • 9
  • 45
  • 95
1

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)

Riyal MHH
  • 58
  • 5
1
//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; }
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
1

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.

Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
0

In WPF the keycode values are different from the normal winforms e.keychar values,

In the PreviewKeyDown event of the textbox, add this code:

if ((e.key < 34) | (e.key > 43)) {
if ((e.key < 74) | (e.key > 83)) {
    if ((e.key == 2)) {
        return;
        }
    e.handled = true;
    }
}

This will allow the User to only enter Numbers in the Numpad0 - Numpad9 section and the D0 - D9 and also the key.Back

Hope this Helps, cheers!

George
  • 411
  • 1
  • 5
  • 6
0
private void shomaretextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
  // xaml.cs code
  if (!char.IsDigit(e.Text, e.Text.Length - 1))
    e.Handled = true;
}

In xaml

<TextBox x:Name="shomaretextBox" 
         HorizontalAlignment="Left" 
         Height="28" 
         Margin="125,10,0,0" 
         TextWrapping="Wrap" 
         VerticalAlignment="Top" 
         Width="151" 
         Grid.Column="1"        
         TextCompositionManager.PreviewTextInput="shomaretextBox_PreviewTextInput" />
Jeroen Heier
  • 3,520
  • 15
  • 31
  • 32
amin zare
  • 23
  • 1
  • 4
  • 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 :) – סטנלי גרונן Apr 09 '17 at 08:52
-1

I believe what you're looking for is the PreviewTextInput event.

Bubblewrap
  • 7,266
  • 1
  • 35
  • 33