C#: How Do I Make A Textbox That Only Accepts Numbers?

To create a textbox that only accepts numbers in C#, you can use the KeyPress event and validate the input. Below is an example code snippet:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // Check if the entered key is a number or a control key
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true; // Handle the key event to discard the input
    }
}

In the above code, the KeyPress event of the textbox is handled. The event is fired whenever a key is pressed. Inside the event handler, the e.KeyChar represents the character input by the user. We use char.IsDigit(e.KeyChar) to check if it is a digit, and char.IsControl(e.KeyChar) to check if it is a control key (e.g., backspace).

When the entered key is not a number or a control key, e.Handled is set to true, which discards the input and prevents it from appearing in the textbox.

To utilize this code, you should assign the textBox1_KeyPress method to the KeyPress event of your textbox. You can do this either in the designer by selecting the textbox, going to the properties window, and finding the KeyPress event, or programmatically in the form’s constructor after initializing the textbox.

textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);

With this implementation, the textbox will only accept numeric input, as any other character entered by the user will be rejected.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!