如何计算asp.net表单中的复选框

ASP.NET:

 

C#:

 foreach (Control item in this.form1.Controls) { 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.
"); } } }

我得到_cbx变量的null值。

如何更新它,以便我能够获取所有checked输入类型复选框的ID。

我尝试了这个答案: 计算表单中TextBox和CheckBoxes的数量,但对我来说也不起作用。

如果要使用则需要解析DOM。

我建议你使用而不是 。 然后你可以从c#访问你的控件

在您的查找中:
var _cbx = item as System.Web.UI.WebControls.CheckBox;

您可以获取所有复选框,而无需循环遍历所有控件。
使用LINQ:
this.form1.Controls.Where(c=>c.GetType() == typeof(CheckBox))

我认为问题是您的复选框不在服务器上运行。 因此,它们在代码隐藏中没有“分配”控件。 尝试将属性runat =“server”添加到您的复选框。 就像你在面板中一样。

用这个:

 foreach (HtmlElement element in webBrowser1.Document.All) { System.Web.UI.HtmlControls.HtmlInputCheckBox _cbx = element as System.Web.UI.HtmlControls.HtmlInputCheckBox; if (_cbx != null) { if (_cbx.Checked) { //Do something: Response.Write(_cbx.Name + " was checked.
"); } } }

首先,您需要添加runat="server"或将它们更改为asp:CheckBox控件。

但是如果添加它们就无法找到它们的原因是因为它们处于另一个控制之下。 所以在pnlFilter寻找它们。

  

代码背后

 foreach (Control item in pnlFilter.Controls) { HtmlInputCheckBox _cbx = item as HtmlInputCheckBox; if (_cbx != null) { if (_cbx.Checked) { //Do something: Response.Write(_cbx.Name + " was checked.
"); } } }

我认为答案是所有建议的变化的组合。 使复选框runat服务器具有可用的服务器端:

  

并按照建议对面板的(子)控件进行交互:

 foreach (Control item in this.pnlFilter.Controls) { 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.
"); } } }

或者,如果您将复选框更改为asp:Checkbox则类型将为System.Web.UI.WebControls.CheckBox

我认为通过前端进程访问前端的东西会更好。

例如,收集JQuery所需的已检查复选框ID,并将它们保存在HiddenField然后按请求获取后端。

  

JQuery部分(首先链接JQuery和json2 lib)

 function recoverCbxStatus() { if (hdfIds.value) { var ids = JSON.parse(hdfIds.value); ids.forEach(function (id) { $('#' + id).prop('checked', true); }); } } function refreshIds() { var ids = []; $('input:checkbox[id^="cb"]:checked').each(function () { ids.push($(this).attr("id")); }); hdfIds.value = JSON.stringify(ids); } $(document).ready(function () { recoverCbxStatus(); refreshIds(); }); $('input:checkbox[id^="cb"]').change(function () { refreshIds(); }); 

后端(Nuget Json.NET)

 protected void Page_Load(object sender, EventArgs e) { string idsJson = Request["hdfIds"]; List ids; if (idsJson != null) { ids = JsonConvert.DeserializeObject>(idsJson); Response.Write("count: " + ids.Count); } } 

您可以使用GridView。 代码方这样做 –

 for (int i = 0; i < **yourGridViewId** .Rows.Count; i++) { CheckBox cb = ((CheckBox)**yourGridViewId** .Rows[i].FindControl(" **yourCheckboxId**")); .... }