ASP.NET遍历textbox文本框
Asp.Net如何遍历所有TextBox控件并清空
asp.net 不能像window那样直接遍历this.Controls就可以了,因为:
- this.Controls只是包含了Page根一级的control,这样次级的control就都没有遍历
- TextBox一般会放在form里面,遍历this.Controls只会访问form control,而不会访问form的子Contorl
下面使用递归对页面control树进行完全遍历
private void ResetTextBox(ControlCollection cc)
{
foreach (Control ctr in cc)
{
if (ctr.HasControls())
{
ResetTextBox(ctr.Controls);
}
if (ctr is TextBox)
{
((TextBox)ctr).Text = string.Empty;
}
}
}
调用
ResetTextBox(this.Controls);
/// <summary>
/// 清空textBox
/// </summary>
/// <param name="ParentControl"></param>
public static void GetChildControlClear(Control ParentControl)
{
if (ParentControl.HasControls())
{
foreach (Control ctl in ParentControl.Controls)
{
if(ctl.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
{
((System.Web.UI.WebControls.TextBox)ctl).Text = "";
}
GetChildControlClear(ctl);
}
}
}
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 }
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>
引用至:http://hi.baidu.com/cuicanrensheng/item/f89eef9d735f59c9b725318e