Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
3.25/5 (4 votes)
See more:
Hi..
I want user to enter only numeric values in textbox.
I got this code:
C#
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.

Whats the solution?
Posted
Updated 17-May-10 20:39pm
v2
Comments
Akinmade Bond 2-Nov-12 12:56pm    
You should use the KeyDown or PreviewKeyDown event. Plus, the code you got is not for WPF, it's for WinForm.
Nelek 2-Nov-12 13:04pm    
Have you noticed that the question is from 2010?
Akinmade Bond 3-Nov-12 8:56am    
Oops. Hadn't noticed. :O

Try this.

C#
private void NumericTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (!Char.IsDigit((char)KeyInterop.VirtualKeyFromKey(e.Key)) & e.Key != Key.Back | e.Key == Key.Space)
    {
        e.Handled = true;
        MessageBox.Show("I only accept numbers, sorry. :(", "This textbox says...");
    }
}



You may need to import System.Windows.Input to get KeyInterop

The code segment above goes into the PreviewKeyDown event of the TextBox.
 
Share this answer
 
Comments
Parteek1991 17-Nov-12 5:53am    
Thankyou Sir...
Akinmade Bond 17-Nov-12 7:43am    
Happy to help. :)
CQüeb 27-Jun-13 18:52pm    
This approach seems good, but allows capture the shift key, causing that characters !"#$%&/()=?¡ becomes to be captured.
anjulanka 11-Jan-15 20:36pm    
This doesn't support NumPad keys
Member 13935090 10-Oct-18 5:26am    
This doesn't work with NumPad Digits
Validations in WPF should be handled using validation rules.
Have a look at this article.
 
Share this answer
 
Comments
Clifford Nelson 2-Nov-12 18:48pm    
That is not necessarily true since cannot deal with context issues with this technology. It works for simple validation, but not validation against other values. Not my vote of 1.
louie_nz 7-Nov-14 18:47pm    
Maybe it's out of date, but responsibly speaking, so far WPF vaidation rules should be the better solution.
KeyPress in winforms was just perfect for input parsing,
unfortunately WPF don't have such event ;(
here my metod for parsing textbox input, allowing to input signed decimal number
(code is sucks but i cant find simpler way)
C#
private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!char.IsNumber(e.Text, e.Text.Length-1))
            {
                e.Handled = true;
            }

            if (( (e.Text).ToCharArray()[e.Text.Length - 1] == '.') || ((e.Text).ToCharArray()[e.Text.Length - 1] == ',')) 
            {
                e.Handled = true;
                if (!(((TextBox)sender).Text.Contains('.')))
                {
                    if (((TextBox)sender).Text.Length == 0) { ((TextBox)sender).Text = "0."; ((TextBox)sender).CaretIndex = ((TextBox)sender).Text.Length; }
                    else { ((TextBox)sender).Text += "."; ((TextBox)sender).CaretIndex = ((TextBox)sender).Text.Length; }
                }
            }
            if ((e.Text).ToCharArray()[e.Text.Length - 1] == '-' & !((TextBox)sender).Text.Contains('-')) { e.Handled = true; ((TextBox)sender).Text = "-" + ((TextBox)sender).Text; ((TextBox)sender).CaretIndex = ((TextBox)sender).Text.Length; }
            if ((e.Text).ToCharArray()[e.Text.Length - 1] == '+' & ((TextBox)sender).Text.Contains('-')) { e.Handled = true; ((TextBox)sender).Text=((TextBox)sender).Text.Substring(1); ((TextBox)sender).CaretIndex = ((TextBox)sender).Text.Length; }
 }
 
Share this answer
 
v2
Comments
Akinmade Bond 2-Nov-12 12:51pm    
There is a simpler way, look at my answer.
Bijay Kant Salotry 13-Nov-13 8:14am    
Thank you...your solution works for me.
Clifford Nelson 2-Nov-12 18:56pm    
Using the PreviewTextInput is not a good idea. KeyDown event works just fine. Also, much too complex for what was asked for. Don't have to worry about signs, or decimal points.
CQüeb 27-Jun-13 18:57pm    
Thank you for this awesome code.. really useful. If someone don't need manage the signs or decimal points.. that adapt the code for his requirements.. we are developers... :)
Hrvoje Batrnek 9-Mar-19 4:53am    
This does not handle space.
Hello,
Try my code its simple

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
//allows only number
            if (char.IsNumber(e.KeyChar) == false)
            {
                e.Handled = true;
            }
//backspace working code
            if (e.KeyChar == (char)Keys.Back)
            {
                e.Handled = false;
            }
        }


Do rate my answer once you find it useful
Thanks & Regards
Radix :rose:
 
Share this answer
 
Comments
Souvik Banerjee 21-Jun-10 1:10am    
Reason for my vote of 1
@Radix: Your code looks like a code for .NET 2.0. In KeyPressEventArgs in WPF, there is no e.KeyChar.
Akinmade Bond 2-Nov-12 11:50am    
Your code would only work in WinForms, sorry.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900