1

我希望能够遍历表单中的所有 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";
            }

        }
4

2 回答 2

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

希望这可以帮助....

于 2013-09-08T17:37:18.390 回答
0

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

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

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

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

编辑: 也许你试试这个:ControlFinder

于 2013-09-08T15:22:18.727 回答