我想清除所有文本框。将公共职能写成:
public void clean(Control parent)
{
try
{
foreach (Control c in parent.Controls)
{
TextBox tb = c as TextBox; //if the control is a textbox
if (tb != null)//Will be null if c is not a TextBox
{
tb.Text = String.Empty;//display nothing
}
}
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
在页面的类中,我希望它被称为声明:
PublicFunctions pubvar = new PublicFunctions();
我将其称为
pubvar.clean(Page);
但它不起作用......甚至没有抛出错误......我的文本框没有清除......帮助?
答案 0 :(得分:0)
您应该使用递归循环来检查所有控件。
试试这段代码
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
public class PublicFunctions
{
public void Clean(Control parent)
{
var controls = GetAllControls(parent);
foreach (Control c in controls)
{
TextBox tb = c as TextBox;
if (tb != null)
{
tb.Text = String.Empty;
}
}
}
public IEnumerable<Control> GetAllControls(Control parent)
{
foreach (Control control in parent.Controls)
{
yield return control;
foreach (Control innerControl in control.Controls)
{
yield return innerControl;
}
}
}
}