I want to restrict a textbox to accept only numbers in C#. How do I do that?
The most crude down and dirty way of doing it is doing something like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar);
}
}
You're still not safe with this approach, as users can still copy and paste non-numeric characters into the textbox. You still need to validate your data regardless.
From others have said before me, we have to almost know what you will use this in, WinForms, ASP.NET, Silverlight ...
But now I take a chance that it is WinForm:)
private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
e.Handled = true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With