Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

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

4.00/5 (1 vote)
2 Oct 2011CPOL 14.4K  
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)