Avatar ·

How to make a text box that accepts only digits (C# WinForms)?

Hello everyone! I'm a beginner in C# and WinForms, making a simple application for entering the user's age. I need the text box to accept only digits, and letters and other characters should be ignored. I tried using int.TryParse after clicking a button, but it's inconvenient — the user can enter "abc123" and only find out about the error after clicking. I want invalid characters to not appear in the field at all during input.

Here's my current code that checks the value on button click:

private void buttonOk_Click(object sender, EventArgs e)\n{\n    string input = textBoxAge.Text;\n    if (int.TryParse(input, out int age))\n    {\n        MessageBox.Show($"Your age: {age}");\n    }\n    else\n    {\n        MessageBox.Show("Enter only digits");\n    }\n}