简体   繁体   中英

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.

使用实现的方法创建派生的DigitsOnlyTextBox,并使用它代替TextBoxes。

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 在VS中添加默认事件处理程序

Copy Def Handler 在VS中添加复制的事件处理程序

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM