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