本主题的部分内容已经涵盖,但我是C#的新手,我无法弄明白。
我有一个强制用户输入带小数
的数字的函数public void onlynumwithsinglepoint(object sender, KeyPressEventArgs e)
{
if (!(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == '.'))
{ e.Handled = true; }
TextBox txtDecimal = sender as TextBox;
if (e.KeyChar == '.' && txtDecimal.Text.Contains("."))
{
e.Handled = true;
}
}
当有KeyPress时,我需要将该函数应用于名为ConcreteFilledColumn()的表单中的每个文本框。我知道有一种方法可以使用"对于每个"陈述......但无法弄明白。现在我的所有文本框都使用单独的事件:
private void columnLengthTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
onlynumwithsinglepoint(sender, e);
}
答案 0 :(得分:2)
这很简单:
public Form1() //your form constructor
{
InitializeComponent();
textbox1.OnKeyDown += onlynumwithsinglepoint; //or whatever the event is
textbox2.OnKeyDown += onlynumwithsinglepoint;
textbox3.OnKeyDown += onlynumwithsinglepoint;
}
至于递归,如果您使用的是WinForms,我猜这样的东西是有效的:
public Form1() //your form constructor
{
InitializeComponent();
foreach(Button b in this.Controls.OfType<Button>())
{
b.OnkeyDown += onlynumwithsinglepoint; //or whatever the event is
}
}