📜  c# textboxaccept only numbers - C# (1)

📅  最后修改于: 2023-12-03 14:39:44.290000             🧑  作者: Mango

C# Textbox Accept Only Numbers

When developing a Windows Forms Application, you often need to restrict user input to only certain types of data. For example, you may need to limit the contents of a textbox to only numeric values. In this tutorial, we will learn how to accept only numbers in a C# Textbox.

Method 1: Using the KeyPress Event

The simplest way to restrict user input to only numbers is by handling the KeyPress event. The KeyPress event is raised each time a character is pressed while the textbox has focus. We can write code in its handler to allow or disallow certain characters.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // Allow only numeric characters and control keys (backspace, delete)
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

In the above example, we check whether the pressed key is a numeric character or a control key (backspace or delete). If it is not, we set the Handled property of the event arguments to true, which blocks the input.

Method 2: Using Regular Expressions

Another way to ensure that a textbox only accepts numbers is by using regular expressions. Regular expressions are a powerful tool for manipulating strings and can be used to restrict user input.

private void textBox1_TextChanged(object sender, EventArgs e)
{
    // Remove any non-numeric characters from the textbox
    textBox1.Text = Regex.Replace(textBox1.Text, "[^0-9]", "");
}

In this example, we handle the TextChanged event of the textbox and use a regular expression to replace any non-numeric characters with an empty string. This effectively removes any non-numeric characters the user may have entered.

Conclusion

In this tutorial, we have learned two approaches to accepting only numbers in a C# Textbox. The first approach uses the KeyPress event to restrict input, and the second approach uses regular expressions to clean up user input. By using these techniques, you can ensure that your Windows Forms application accepts only valid user input.