Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Tagged as

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

, 2 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.
 
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)

Share

About the Author

endozs
Systems Engineer Stratco
Australia Australia
I'm an Aircraft Maintenance Engineer gone wild.
After leaving the Air Force I studied Business Info Systems at university and am now working as an automation expert.
 
Primarily on automation control systems, Factory SCADA, Human Machine interface.
 
Basically have free reign to improve /build new our manufacturing systems so the work is fun, a nice blend of software and hardware.
 
Admin for a handful of servers across the country, web master, db admin, maintenance, problem solver, magician, ninja.....
 
Think Jack of all trades master of none Smile | :)

Comments and Discussions

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

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150129.1 | Last Updated 2 Oct 2011
Article Copyright 2011 by endozs
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid