Sarah Sarah - 1 year ago 99
C# Question

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!

Answer Source

try this code snippet

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

    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;
        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("The Value You entered is : " + _val);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download