悬赏分:20 浏览:626 次
请问大家如何实现在winform中对textbox控件的非空验证呢?
以前在asp.net中很方便,有验证控件,拿来用就行了。不知道在winform中该如何实现?
|
哥们,
if(textbox.text.lenght==0)
{
//do something.
} [code] if(String.IsNullOrEmpty(textbox.Text) || textbox.Text.Trim() == string.Empty){ MessageBox.Show("请输入xxx"); return; } [/code] foreach(Control ctl in this.Controls[1].Controls) { if(ctl.GetType().Name=="TextBox") { TextBox tb =new TextBox(); tb=(TextBox)this.FindControl(ctl.ID); if(tb.Text==string.Empty) { Response.Write("<script>alert('" + ctl.ID + "的值为空。');</script>"); break; } } } 自己写代码实现。 因为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. } 三楼是常用的做法。 @生鱼片 winform下也能用Response? 另外,个有感觉做验证还是正则式比较方便 |
|
6个月前 lemontree : 如果有很多个文本框,一次提交该怎么验证? |