Loop through all html checkboxes in form

Jawaid Akhtar picture Jawaid Akhtar · Sep 8, 2013 · Viewed 9.2k times · Source

I would like to be able loop through all the html checkboxes in my form and if it is checked do something else do something else. I also would like to do this in the code behind not using any Javascript\jquery.

<form id="form1" runat="server">
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    <div>
  <table width="850" border="0" cellpadding="0" cellspacing="10" class="Copy" >
    <tr>
      <td valign="top"><table width="200" border="0" cellspacing="0" cellpadding="3" bgcolor="#f0f4f8">
          <tr>
            <td width="21">&nbsp;</td>
            <td width="179"><strong>CheckBoxes</strong></td>
          </tr>
          <tr>
            <td><input runat="server" type="checkbox" name="checkbox1" id="checkbox1" /></td>
            <td>checkbox1</td>
          </tr>
          <tr>
            <td><input runat="server" type="checkbox" name="checkbox2" id="checkbox2" /></td>
            <td>checkbox2</td>
          </tr>
          <tr>
            <td><input runat="server" type="checkbox" name="checkbox3" id="checkbox3" /></td>
            <td>checkbox3</td>
          </tr>
        </table>
    </div>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
    </form>

In the codebehind I have tried a couple of different ways but i am guessing since it is an HTML Input control of type Checkbox it is not working

 foreach (CheckBox chk in Page.Form.Controls.OfType<CheckBox>())
        {

            if (chk.Checked == true)
            {
                Label1.Text = "we have checkboxes";
            }
            else
            {
                Label1.Text = "Still no checkboxes";
            }

        }

Answer

EdSF picture EdSF · Sep 8, 2013

A couple of ways:

foreach (Control item in this.form1.Controls)
{
    //We just need HtmlInputCheckBox 
    System.Web.UI.HtmlControls.HtmlInputCheckBox _cbx = item as System.Web.UI.HtmlControls.HtmlInputCheckBox;
    if (_cbx != null)
    {
        if (_cbx.Checked)
        {
            //Do something: 
            Response.Write(_cbx.Name + " was checked.<br />");
        }
    }

}

or

//We just need HtmlInputCheckBox
IEnumerable<Control> _ctrls = from Control n in this.form1.Controls where n as System.Web.UI.HtmlControls.HtmlInputCheckBox != null select n;

if (_ctrls.Count() > 0)
{
    foreach (System.Web.UI.HtmlControls.HtmlInputCheckBox item in _ctrls)
    {
        if (item.Checked)
        {
            //Do something:
            Response.Write(item.Name + " was checked.<br/><br />");
        }
    }
}

Hope this helps....