Search code examples
c#asp.netforeachweb-controls

How do I do a FOREACH loop on specific controls on my web form?


This is basically what I want to do:

foreach (checkbox cbx in Controls.Checkboxes)
{
    if (checkbox.checked)
       {
            //code
       }
}

On my web page, there are 2 check boxes. I want to run a process for each selected item on the page.


Solution

  • If I understand your question correctly, you want to loop through each checkbox of checkboxlist control and get the values.

    If so, here is an example.

    <asp:CheckBoxList runat="server" ID="CheckBoxList1">
        <asp:ListItem Text="One" Value="1" />
        <asp:ListItem Text="Two" Value="2" />
        <asp:ListItem Text="Three" Value="3" />
    </asp:CheckBoxList>
    <asp:Button runat="server" ID="Button1" Text="Submit" OnClick="Button1_Click" />
    
    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (ListItem item in CheckBoxList1.Items)
        {
            if (item.Selected)
            {
                string text = item.Text;
                string value = item.Value;
                // Do something
            }
        }
    }
    

    If you are asking about individual checkboxes, click on my previous edited answer.