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.
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
Copy Def Handler