asp.net遍历页面中所有TextBox,并赋值为String.Empty的方法
一、遍历窗体控件
1,普通页面遍历TextBox控件清空的方法
{
if(c is TextBox)
{
TextBox tb=(TextBox)c;
tb.Text=String.empty;
}
}
//或
foreach (Control col in this.Controls)
{
if (col.GetType().Name.Equals("TextBox"))
{
((TextBox)col).Text = String.empty;
}
}
二、遍历Asp.net页面
//不含母板页
foreach (System.Web.UI.Control txtobj in this.Page.Controls)
{
if (txtobj.GetType().Name .Equals("TextBox"))
{
// ((TextBox)txtobj).Text = String.Empty;//这是第一种方法赋值,第二种在下面
TextBox tb = new TextBox();
tb = (TextBox)this.FindControl(txtobj.ID);
tb.Text = String.Empty;
}
}
包含母板页
//套用母版页的页面遍历TextBox控件的方法,其他控件类似
foreach (Control cp in Page.Controls)
{
foreach (System.Web.UI.Control ct in cp.Controls)
{
if (ct is HtmlForm)
{
foreach (Control con in ct.Controls)
{
foreach (Control c in con.Controls)
{
if (c is TextBox)
{
(c as TextBox).Text = String.Empty;
}
}
}
}
}
}
三、清除控件内容
//public static void ClearAllContent()
//清空指定页面上所有的控件内容
//包括TextBox,CheckBox,CheckBoxList,RadioButton,RadioButtonList。不过不清
//除如ListBox,DropDownList,因为这样的控件值对当前页面来说还能用,一般这些控件里都是保存的字典数据。
//<param name="page"> 指定的页面</param>
public static void ClearAllContent(System.Web.UI.Control page)
{
int nPageControls = page.Controls.Count;
for (int i = 0; i < nPageControls; i++)
{
foreach (System.Web.UI.Control control in page.Controls[i].Controls)
{
if (control.HasControls())
{
ClearAllText(control);
}
else
{
if (control is TextBox)
(control as TextBox).Text = "";
if (control is CheckBox)
(control as CheckBox).Checked = false;
if (control is RadioButtonList)
(control as RadioButtonList).SelectedIndex = -1;
if (control is RadioButton)
(control as RadioButton).Checked = false;
if (control is CheckBoxList)
{
foreach (ListItem item in (control as CheckBoxList).Items)
{
item.Selected = false;
}
}
}//if..else
}//foreach
}//for
}
附,如何在ASP.NET下遍历指定页面上所有控件
#region 清空指定页面上所有的控件内容,public static void ClearAllContent()
/// <summary>
/// 清空指定页面上所有的控件内容,包括TextBox,CheckBox,CheckBoxList,RadioButton,RadioButtonList。但是不清
/// 除如ListBox,DropDownList,因为这样的控件值对当前页面来说还可以用,一般这些控件里都是保存的字典数据。
/// Author:Kevin
/// www.jbxue.com
/// </summary>
/// <param name="page"> 指定的页面</param>
public static void ClearAllContent(System.Web.UI.Control page)
{
int nPageControls = page.Controls.Count;
for (int i = 0; i < nPageControls; i++)
{
foreach (System.Web.UI.Control control in page.Controls[i].Controls)
{
if (control.HasControls())
{
ClearAllText(control);
}
else
{
if (control is TextBox)
(control as TextBox).Text = "";
if (control is CheckBox)
(control as CheckBox).Checked = false;
if (control is RadioButtonList)
(control as RadioButtonList).SelectedIndex = -1;
if (control is RadioButton)
(control as RadioButton).Checked = false;
if (control is CheckBoxList)
{
foreach (ListItem item in (control as CheckBoxList).Items)
{
item.Selected = false;
}
}
}//if..else
}//foreach
}//for
}
#endregion