因为WinForm不需要复杂的Postback机制,性能方面很容易把握,所以,简单的Validation组件并不需要。
如果你希望如果TextBox的Text为空,就不能够失去Focus(就是光标不会离开),可以挂接TextBox.Validating事件,如下:
void Form_Load(object sender, EventArgs e)
{
this.textBox1.Validating += new CancelEventHandler(textBox_Validating);
this.textBox2.Validating += new CancelEventHandler(textBox_Validating);
this.textBox3.Validating += new CancelEventHandler(textBox_Validating);
}
void textBox_Validating(object sender, CancelEventArgs e)
{
TextBox textBox = sender as TextBox;
e.Cancel = string.IsNullOrEmpty(textBox.Text);
}
如果你希望验证所有的textBox控件在button click事件里,可以如下:
void button_Click(object sender, EventArgs e)
{
foreach (Control control in this.Controls)
{
if (control is TextBox && string.IsNullOrEmpty(control.Text))
{
return;
}
}
// Do you commit logic.
}