Asp.net中一次性清空页面上的所有TextBox中的内容,由于TextBox在客户端以<input type=”text”>形式来呈现的,因此解决方案有客户端和服务器端两种方式,服务器端包括两种方法!这个破东西在网上的asp.net面试题中广为流传,于是今天下午在看面试题的时候搞了一把。
直接贴出代码来吧,都经过测试过了
方法一:
Code
1foreach (Control c in this.FindControl("form1").Controls)
2{
3 if (c is TextBox)
4 {
5 ((TextBox)c).Text = "";
6 }
7}
8
9
10
1foreach (Control c in this.FindControl("form1").Controls)
2{
3 if (c is TextBox)
4 {
5 ((TextBox)c).Text = "";
6 }
7}
8
9
10
方法二:
Code
1 FieldInfo[] infos = GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
2 for (int i = 0; i < infos.Length; i++)
3 {
4 if (infos[i].FieldType == typeof(TextBox))
5 {
6 ((TextBox)infos[i].GetValue(this)).Text = "";
7 }
8 }
1 FieldInfo[] infos = GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
2 for (int i = 0; i < infos.Length; i++)
3 {
4 if (infos[i].FieldType == typeof(TextBox))
5 {
6 ((TextBox)infos[i].GetValue(this)).Text = "";
7 }
8 }
方法三:(客户端事件)
Code
1<script language="javascript" type="text/javascript">
2 function ClearAllTextBox() {
3 var obj = window.document.forms[0];
4 for (i = 0; i < obj.elements.length; i++) {
5 var elem = obj.elements[i];
6 if (elem) {
7 if (elem.type == "text") {
8 elem.value = "";
9 }
10 }
11 }
12 }
13 </script>
1<script language="javascript" type="text/javascript">
2 function ClearAllTextBox() {
3 var obj = window.document.forms[0];
4 for (i = 0; i < obj.elements.length; i++) {
5 var elem = obj.elements[i];
6 if (elem) {
7 if (elem.type == "text") {
8 elem.value = "";
9 }
10 }
11 }
12 }
13 </script>