首页 新闻 赞助 找找看

winform中的textbox非空验证

0
悬赏园豆:20 [已解决问题] 解决于 2009-03-02 15:20
<P>请问大家如何实现在winform中对textbox控件的非空验证呢?<BR><BR>以前在asp.net中很方便,有验证控件,拿来用就行了。不知道在winform中该如何实现?</P>
lemontree的主页 lemontree | 初学一级 | 园豆:0
提问于:2008-05-28 17:17
< >
分享
最佳答案
1
因为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. }
Colin Han | 老鸟四级 |园豆:3041 | 2008-05-29 13:31
其他回答(6)
0
哥们, if(textbox.text.lenght==0) { //do something. }
jason wei | 园豆:230 (菜鸟二级) | 2008-05-28 17:28
0
[code] if(String.IsNullOrEmpty(textbox.Text) || textbox.Text.Trim() == string.Empty){ MessageBox.Show("请输入xxx"); return; } [/code]
玉开 | 园豆:8822 (大侠五级) | 2008-05-28 17:35
0
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; } } }
生鱼片 | 园豆:5757 (大侠五级) | 2008-05-29 07:59
0
自己写代码实现。
李.net | 园豆:730 (小虾三级) | 2008-05-29 09:14
0
三楼是常用的做法。
伽马科技.攻城师 | 园豆:1303 (小虾三级) | 2008-05-29 15:22
0
@生鱼片 winform下也能用Response? 另外,个有感觉做验证还是正则式比较方便
张荣华 | 园豆:2020 (老鸟四级) | 2008-05-29 16:43
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册