循环遍历表单中的所有html复选框

时间:2013-09-08 14:47:33

标签: c# asp.net html5 runatserver

我希望能够遍历我表单中的所有html复选框,如果选中它,请执行其他操作。我也想在不使用任何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>

在代码隐藏中,我尝试了几种不同的方法,但我猜是因为它是一个类型为Checkbox的HTML输入控件,它无法正常工作

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

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

        }

2 个答案:

答案 0 :(得分:3)

有两种方式:

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 />");
        }
    }

}

//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 />");
        }
    }
}

希望这会有所帮助......

答案 1 :(得分:0)

如果您知道CheckBoxes的ID,可以尝试使用:FindControl Control.FindControl-Methode (String)

这不是一个很好的解决方案,biut尝试使用它:

bool cFound = true;
while(cFounnd)
{
    var cCheckBox = this.FindControl(...);

    if(cCheckBox != null)
    {
        ....
    }
    else
    {
        cFound = false;
    }
}

修改 也许你试试这个:ControlFinder