Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through Checkboxes in Placholder

I'm trying to find a way to loop through all the controls of type 'Checkbox' in a ASP Placeholder, and then do something with the control in the loop.

Problem is I can't access the controls...here is what I have so far...

string selections = "";

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

But I'm getting the error - "Foreach cannot operate on a method group".

Any help would be greatly appreciated.

Thanks.

like image 873
Adam92 Avatar asked Jan 07 '14 21:01

Adam92


1 Answers

OfType is a method so you have to add ():

foreach (CheckBox ctrl in phProductLines.Controls.OfType<CheckBox>())
{
    // ...
}

By the way, you can use LINQ and String.Join to get your desired result:

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

If you only want the Checked checkboxes:

string result = string.Join(", ", phProductLines.Controls.OfType<CheckBox>()
            .Where(chk => chk.Checked)
            .Select(chk => chk.Text));
like image 166
Tim Schmelter Avatar answered Nov 06 '22 16:11

Tim Schmelter