65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Sep 21, 2011

CPOL
viewsIcon

14516

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";
            }             
        }