Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restricting textbox input to numbers in C# [closed]

Tags:

c#

I want to restrict a textbox to accept only numbers in C#. How do I do that?

like image 815
ibrahim Avatar asked Aug 31 '25 03:08

ibrahim


2 Answers

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.

like image 89
BFree Avatar answered Sep 02 '25 16:09

BFree


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;
}
like image 44
eriksv88 Avatar answered Sep 02 '25 17:09

eriksv88