Asp.Net如何遍歷所有TextBox控件並清空





Asp.Net如何遍歷所有TextBox控件並清空

http://hi.baidu.com/cuicanrensheng/item/f89eef9d735f59c9b725318e

asp.net 不能像window那樣直接遍歷this.Controls就可以了,因為:

  1. this.Controls只是包含了Page根一級的control,這樣次級的control就都沒有遍歷
  2. 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>


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com