asp教程.net winform textbox事件的组合代码
功能需求:
用户名不能为空
用户的年龄必须是一个大于或等于0的数字;
用户的地址不能为空
用户的职务必须是“software”或者为空
这个功能中我们用到了textchanged,keypress,validating事件;根据功能要求,可知用户名文本框和用户的地址的文本框用到同一个事件emptyvalidating来判断文本框是否为空;
在这个功能用用到空间的tag属性,用此来设置控件的有关数据,我们在构造函数中设置用户名文本框,用户地址文本框,用户年龄文本框,用户职务文本框的tag的值为false。
用到keypress事件--在不想要的字符在文本框中显示出来之前就删除它们。
1 public partial class form1 : form
2 {
3 public form1()
4 {
5 initializecomponent();
6 this.button1.enabled = false;
7 }
8
9 private void emptyvalidating(object sender, canceleventargs e)
10 {
11 textbox tb = (textbox)sender;
12 if (tb.text.length == 0)
13 {
14 tb.backcolor = color.red;
15 tb.tag = false;
16 }
17 else
18 {
19 tb.backcolor = systemcolors.window;
20 tb.tag = true;
21 }
22 validateok();
23 }
24 public void validateok()
25 {
26 this.button1.enabled = (bool)this.txtname.tag && (bool)this.txtaddress.tag && (bool)this.txtage.tag && (bool)this.txtoccuption.tag;
27 }
28
29 private void txtoccuption_validating(object sender, canceleventargs e)
30 {
31 textbox tb = (textbox)sender;
32 if (tb.text.length == 0 || tb.text.compareto("software") == 0)
33 {
34 tb.tag = true;
35 tb.backcolor = systemcolors.window;
36
37 }
38 else
39 {
40 tb.tag = color.red;
41 tb.backcolor = color.red;
42 }
43 validateok();
44 }
45
46 private void txtage_keypress(object sender, keypresseventargs e)
47 {
48 if ((e.keychar < 48 || e.keychar > 57) && e.keychar != 8)
49 {
50 e.handled = true;
51
52 }
53
54
55 }
56
57 private void txtage_validating(object sender, canceleventargs e)
58 {
59 textbox tb = (textbox)sender;
60 if (tb.text.length == 0)
61 {
62 tb.tag = false;
63 tb.backcolor = color.red;
64 }
65 else
66 {
67 tb.tag = true;
68 tb.backcolor = systemcolors.window;
69 }
70 validateok();
71 }
72
73 private void messagechanged(object sender, eventargs e)
74 {
75 textbox tb = (textbox)sender;
76 if (tb.text.length == 0 && tb.name != "txtoccuption")
77 {
78 tb.tag = false;
79 tb.backcolor = color.red;
80 }
81 else if (tb.name == "txtoccuption" && (tb.text.length != 0 && tb.text.compareto("software") != 0))
82 {
83 tb.tag = false;
84 //tb.backcolor = color.red;
85 }
86 else
87 {
88 tb.tag = true;
89 tb.backcolor = systemcolors.window;
90 }
91 validateok();
92 }
93
94 private void button1_click(object sender, eventargs e)
95 {
96 this.txtoutput.text = "";
97 this.txtoutput.text +="姓名:"+ this.txtname.text + "rn" +"地址:"+ this.txtaddress.text + "rn" +"职务:"+ this.txtoccuption.text + "rn" +"年龄:"+ this.txtage.text;
98 }
99 }