Sunday 8 September 2013

Simplest method to check if the string entered in a TextBox in C# application contain only numbers(0-9) i.e. the string is numeric

I bet you, you won't find this simplest method to check if TextBox contains only numbers anywhere else on the whole net.

Suppose the name of our TextBox is 'textBox1'.

int numeric=0;
foreach (char ch in textBox1.Text)     //loop through each character of the string entered in textBox1
{
     if (ch >= '0' && ch <= '9')     //check if character falls between 0-9
          {
                numeric++;                 //increment on finding each numeric character
          }
}
if(numeric==textBox1.Text.Length)     //true if all the characters of string are numeric i.e. the textBox1 contains only numbers
{
     //Implement your code here
}
           
        //You could also use the same logic to check if certain number of characters are numeric in string i.e. if(numeric==str.Length)

You can also make a class library and save this code in it and use it wherever needed.

public class CheckTextBox
    {
        public static bool AllNumbers(string str) //Pass thextBox1.Text as parameter
        {
            int numeric = 0;
            foreach (char ch in str)
            {
                if (ch >= '0' && ch <= '9')
                {
                    numeric++;
                }
            }
            if (numeric == str.Length)
            {
                return true;
            }
            else
            {
                return false;  //Use the returned bool type values to check if all characters are numeric. If true is returned, all characters are numeric. If false is returned, all values are not numeric.
            }
        }
    }

No comments:

Post a Comment