To Test Whether a Given Number Entered in a TextBox is Valid Integer or an Invalid Integer

In this blog we will see how to test whether a given number entered in a textbox is a valid integer or an invalid integer.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace Valid_or_Invalid_integer

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void btn_valid_invalid_Click(object sender, EventArgs e)

        {

            int i;

            bool isValidInteger = int.TryParse(textBox1.Text, out i);

            if (!isValidInteger)

            {

                MessageBox.Show("Not a valid integer.Please enter once again!");

                textBox1.Focus();

                return;

            }

            else

            {

                MessageBox.Show("Valid integer");

                textBox1.Focus();

            }

        }

    }

}

Ebook Download
View all
Learn
View all