Joe Goddard
Joe Goddard

Reputation: 27

I want make all textboxes on my form to accept only numbers with as little code as possible - c#

I am making a relatively simple bit of software which has quite a few textboxes and i want a way to only allow numbers in all textboxes in the form with hopefully one piece of code. I am currently using the following code to only allow numbers for one textbox but it means repeating those lines for each textbox.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

The textboxes are also inside a panel incase that makes a difference.

Upvotes: 2

Views: 548

Answers (3)

OhBeWise
OhBeWise

Reputation: 5454

As Darek said, one viable option is to:

Create a derrived DigitsOnlyTextBox, with the method implemented, and use it in place of TextBoxes

A second option is to simply point each TextBox to the same event handler. For example, in the Form.Designer.cs:

this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBoxNumericOnly_KeyPress);
this.textBox2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBoxNumericOnly_KeyPress);
this.textBox3.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBoxNumericOnly_KeyPress);
...

Then your handler:

private void textBoxNumericOnly_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

Assuming you're using Visual Studios and you've already created the event handler the first time (for textBox1), you can easily do this all in the designer view of the Form:

A Default Handler Adding default event handler in VS

Copy Def Handler Adding copied event handler in VS

Upvotes: 1

Simon Brown
Simon Brown

Reputation: 26

If you're using Windows Forms and not WPF you can use a MaskedTextBox.

Not sure if you can replicate the capability in WPF, having never used it.

Upvotes: 0

Darek
Darek

Reputation: 4797

Create a derrived DigitsOnlyTextBox, with the method implemented, and use it in place of TextBoxes.

Upvotes: 2

Related Questions