我正在尝试编写一个公共(public)函数,该函数可以在我的所有页面中调用以在插入数据后清除我的所有文本框。我是这样使用它的:
public void clean(Control parent)
{
try
{
foreach (Control c in parent)
{
TextBox tb = c as TextBox; //if the control is a textbox
tb.Text = String.Empty; //display nothing
}
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
}
但是,foreach 出现错误提示
“无法对变量类型 system.web.ui.control 进行操作,因为它不包含 getenumerator 的公共(public)函数。
谁能提出替代方案?
最佳答案
解决方案
你想迭代parent
的子控件,所以使用这个:
foreach (Control c in parent.Controls)
{
//Do Stuff
}
推荐
我还建议检查控件是否也是 TextBox
...
TextBox tb = c as TextBox;
if(tb != null)//Will be null if c is not a TextBox
{
tb.Text = String.Empty;
}
或
if(c is TextBox)//Check if c is TextBox before using it
{
TextBox tb = c as TextBox;
tb.Text = String.Empty;
}
(有关两种方法之间差异的良好讨论和链接,请参阅评论)
关于c# - 试图找到 foreach 的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20122094/