Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I only allow number input into my C# Console Application?

Console.WriteLine("Enter the cost of the item");                           
string input = Console.ReadLine();
double price = Convert.ToDouble(input);

Hello, I want the keyboard buttons, A-Z, brackets, question mark, etc to be disabled. I want it so if you type it in, it will not show up in the Console. I only want the numbers 1-9 to show up. This is in C# Console application. Thanks for the help!

like image 306
Sarah Avatar asked Oct 28 '12 05:10

Sarah


2 Answers

try this code snippet

string _val = "";
Console.Write("Enter your value: ");
ConsoleKeyInfo key;

do
{
    key = Console.ReadKey(true);
    if (key.Key != ConsoleKey.Backspace)
    {
        double val = 0;
        bool _x = double.TryParse(key.KeyChar.ToString(), out val);
        if (_x)
        {
            _val += key.KeyChar;
            Console.Write(key.KeyChar);
        }
    }
    else
    {
        if (key.Key == ConsoleKey.Backspace && _val.Length > 0)
        {
            _val = _val.Substring(0, (_val.Length - 1));
            Console.Write("\b \b");
        }
    }
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);

Console.WriteLine();
Console.WriteLine("The Value You entered is : " + _val);
Console.ReadKey();
like image 89
John Woo Avatar answered Dec 02 '22 00:12

John Woo


This MSDN article explains how to read characters one at a time in a console window. Test each character as it is input with the Char.IsNumber() method, and reject those characters that fail the test.

like image 34
Robert Harvey Avatar answered Dec 02 '22 01:12

Robert Harvey