Click here to Skip to main content
15,881,559 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Validate numeric textbox using int.tryparse visual C#.NET

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
2 Oct 2011CPOL 13.7K   2   6
You could always run the TryParse on the keyDown event so as to validate as the data gets entered. It saves the user an additional UI interaction. private void textBox1_KeyDown(object sender, KeyEventArgs e) { int i; string s = string.Empty; ...
You could always run the TryParse on the keyDown event so as to validate as the data gets entered. It saves the user an additional UI interaction.

C#
private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            int i;

            string s = string.Empty;

            s += (char)e.KeyValue;

             if (!(int.TryParse(s, out i)))
            {
                e.SuppressKeyPress = true;
                textBox2.Text = "An int, that key press would not create";
            }
            else
            {
                textBox2.Text = "On the path to a great int, you are";
            }             
        }

License

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


Written By
Systems Engineer Stratco
Australia Australia
This member doesn't quite have enough reputation to be able to display their biography and homepage.

Comments and Discussions

 
GeneralRe: Ahh, of course (Slaps palm against forehead), rather foolish... Pin
endozs25-Sep-11 12:25
endozs25-Sep-11 12:25 
GeneralRe: Not quite. Two examples: 1) If the textbox contains 21474836... Pin
Luc Pattyn24-Sep-11 17:04
sitebuilderLuc Pattyn24-Sep-11 17:04 
GeneralRe: thanks endozs Pin
Aria Wijaya24-Sep-11 16:46
Aria Wijaya24-Sep-11 16:46 
GeneralThat is incorrect, your code is assuming the caret is at the... Pin
Luc Pattyn21-Sep-11 6:55
sitebuilderLuc Pattyn21-Sep-11 6:55 
GeneralRe: Hi Luc, thanks for the feedback, although I don't necessaril... Pin
endozs21-Sep-11 11:24
endozs21-Sep-11 11:24 
GeneralRe: thank you for posting this Pin
Aria Wijaya24-Sep-11 16:45
Aria Wijaya24-Sep-11 16:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.