c# - 试图找到 foreach 的替代品

标签 c# foreach

我正在尝试编写一个公共(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/

相关文章:

c# - 按钮单击 MVC 后的部分加载

c# - 代码契约(Contract) : How to express these conditions?

php - Laravel 5 如何在循环中循环

php foreach 多维数组递归不起作用?

JavaScript forEach 语法和长度

c# - 导出Excel错误: File you are trying to open FileName is in different format than specified extension

c# - 不同选定项目的 WPF 组合框背景

c# - 无法在第二台计算机上解密数据

jquery 在 foreach 循环期间从数组中删除元素

php - 如何向数据库中插入多个数组?