07 September 2015

Only allow digits in Console Application in C#

If you are writing a console application in C# and you want to restrict user to only enter digits for certain variable there is an option to use ConsoleKeyInfo struct to read each key user input and take action accordingly. This struct provides a way to find which key user has entered in console application and check if it is a number or not using Char.IsNumber() method.
Below is the complete source code that only allow user to enter digits for a field. If user type any other characters it simply ignores them.

 
Console.WriteLine("Enter Numeric Value : ");
ConsoleKeyInfo key;
string inputStr = "";
do
{
 key = Console.ReadKey(true);
 if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
 {
  if (char.IsNumber(key.KeyChar))//Check if it is a number
  {
   inputStr += key.KeyChar;
   Console.Write(key.KeyChar);
  }
 }
 else
 {
  if (key.Key == ConsoleKey.Backspace && inputStr.Length > 0)
  {
   inputStr = inputStr.Substring(0, (inputStr.Length - 1));
   Console.Write("\b \b");
  }
 }

} while (key.Key != ConsoleKey.Enter);

Console.WriteLine("\nNumber you entered is {0}", inputStr);

No comments:

Post a Comment