foreach循环清空页面全部textbox控件的值的问题
我在项目中想将页面的textbox控件全部清空,控件很多逐个清空很繁杂,现在用foreach循环:
foreach (Control ctl in this.Controls)
if (ctl is TextBox)
{ ((TextBox)ctl).Text = " "; }
运行后不成功,跟总调试发现代码没有执行{ ((TextBox)ctl).Text = " "; }这个语句,而是来回的执行上面一部分,foreach (Control ctl in this.Controls)
if (ctl is TextBox),请各位网友帮忙分析。
------解决方案--------------------void ClearControl(Control x)
{
foreach (Control ctl in x.Controls)
{
if (ctl is TextBox)
{ ((TextBox)ctl).Text = " "; }
if(ctl.Controls.Count>0)
{
ClearControl(ctl );//递归
}
}
}
ClearControl(Page.Form)
------解决方案--------------------页面的控件层次类似于一棵倒立的树,你要递归地查找才行。
C# code
protected void Page_Load(object sender, EventArgs e)
{
Reset(this.Page);
}
public void Reset(Control control)
{
foreach (Control ctl in control.Controls)
{
if (ctl is TextBox)
{
TextBox tb = ctl as TextBox;
tb.Text = string.Empty;
}
if (ctl.HasControls())
Reset(ctl);
}
}
------解决方案--------------------
C# code
foreach(System.Web.UI.Control ctl in this.Form.Controls){
Response.Write(ctl.ToString()+"<br />");
if (ctl is System.Web.UI.WebControls.TextBox)
{
System.Web.UI.WebControls.TextBox tb = (System.Web.UI.WebControls.TextBox)ctl;
tb.Text = string.Empty;
}
}
------解决方案--------------------