[英]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: 正如Darek所说,一个可行的选择是:
Create a derrived DigitsOnlyTextBox, with the method implemented, and use it in place of TextBoxes 创建派生的DigitsOnlyTextBox,并实现该方法,并使用它代替TextBoxes
A second option is to simply point each TextBox
to the same event handler. 第二个选择是简单地将每个TextBox
指向相同的事件处理程序。 For example, in the Form.Designer.cs
: 例如,在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
: 假设您正在使用Visual Studios,并且已经第一次创建了事件处理程序(针对textBox1
),则可以在Form
的设计器视图中轻松完成所有操作:
A Default Handler 默认处理程序
Copy Def Handler 复制Def处理程序
If you're using Windows Forms and not WPF you can use a MaskedTextBox . 如果您使用的是Windows窗体而不是WPF,则可以使用MaskedTextBox 。
Not sure if you can replicate the capability in WPF, having never used it. 不知道您是否可以在WPF中复制该功能,而从未使用过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.