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#.
- 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;
}
}
- 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 = "";
}
}
- 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.