在占位符中循环复选框

5

我想找到一种方法来遍历 ASP Placeholder 中所有类型为“Checkbox”的控件,然后在循环中处理控件。

问题在于我无法访问控件...以下是我的代码...

string selections = "";

foreach (CheckBox ctrl in phProductLines.Controls.OfType<CheckBox>)
{
     selections += ctrl.Text + ", ";            
}

但我遇到了“Foreach cannot operate on a method group”错误。
非常感谢你的帮助。
谢谢。
1个回答

7
OfType是一个方法,因此您需要添加()
foreach (CheckBox ctrl in phProductLines.Controls.OfType<CheckBox>())
{
    // ...
}

顺便说一下,您可以使用LINQ和String.Join来获得所需的结果:
string result = string.Join(", ", phProductLines.Controls.OfType<CheckBox>()
            .Select(chk => chk.Text));

如果你只想要被选中的复选框:

Checked 是可用的。

string result = string.Join(", ", phProductLines.Controls.OfType<CheckBox>()
            .Where(chk => chk.Checked)
            .Select(chk => chk.Text));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接