What are the methods to only allow input of numbers in a C# TextBox?

There are only a few ways to input numbers in C#.

  1. By using the KeyPress event, you can filter input to only allow numerical values. You can determine whether to accept input by checking if the character entered is a number in the KeyPress event.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}
  1. With the TextChanged event, you can check if the input is a number every time the text box content changes and handle it accordingly.
private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (!int.TryParse(textBox1.Text, out int result))
    {
        textBox1.Text = "";
    }
}
  1. You can use regular expressions to validate input as numbers and process them when necessary.
private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (!Regex.IsMatch(textBox1.Text, @"^\d+$"))
    {
        textBox1.Text = "";
    }
}

The above methods can be chosen based on specific needs to implement the functionality of allowing only numerical input.

bannerAds