计算表单中TextBox和CheckBoxes的数量

我的要求是当用户点击'btnGetCount'时,直接在表单内部使用id="form1"计算TextBox和CheckBox的总数。 这是我尝试过的代码,但它没有计算任何东西,并且计数器保持为零,尽管我在表单中有三个TextBox和两个CheckBox。 但是,如果我删除foreach循环并传递TextBox control = new TextBox(); 而不是当前代码然后它计算第一个TextBox和countTB返回值为一。

 protected void btnGetCount_Click(object sender, EventArgs e) { Control control = new Control(); int countCB = 0; int countTB = 0; foreach (Control c in this.Controls) { if (control.GetType() == typeof(CheckBox)) { countCB++; } else if (control is TextBox) { countTB++; } } Response.Write("No of TextBoxes: " + countTB); Response.Write("
"); Response.Write("No of CheckBoxes: " + countCB); }

您必须递归循环其他控件。

  
protected void Page_Load(object sender, EventArgs e) { var controls = form1.Controls; var tbCount = 0; var cbCount = 0; CountControls(ref tbCount, controls, ref cbCount); Response.Write(tbCount); Response.Write(cbCount); } private static void CountControls(ref int tbCount, ControlCollection controls, ref int cbCount) { foreach (Control wc in controls) { if (wc is TextBox) tbCount++; else if (wc is CheckBox) cbCount++; else if(wc.Controls.Count > 0) CountControls(ref tbCount, wc.Controls, ref cbCount); } }

它允许您为零,因为您计算的Control控件的类型不可用,请将您的代码更改为:

 protected void btnGetCount_Click(object sender, EventArgs e) { int countCB = 0; int countTB = 0; foreach (Control c in this.Controls) { if (c.GetType() == typeof(CheckBox)) { countCB++; } else if (c.GetType()== typeof(TextBox)) { countTB++; } } Response.Write("No of TextBoxes: " + countTB); Response.Write("
"); Response.Write("No of CheckBoxes: " + countCB); }

我相信你必须是递归的, this.Controls只会返回它的直接子this.Controls的控件。 如果TextBox位于其中的控件组内,则还需要查看容器控件。

请参阅此其他stackoverflow的答案: 如何获取特定类型(Button / Textbox)的Windows窗体表单的所有子控件?

编辑:我意识到答案是WinForms,但解决方案仍然适用。

只是通过对Alyafey,pcnThird和Valamas建议的代码做一些小改动,我编写了这个有效的代码。

 protected void btnGetCount_Click(object sender, EventArgs e) { int countCB = 0; int countTB = 0; foreach (Control c in form1.Controls) //here is the minor change { if (c.GetType() == typeof(CheckBox)) { countCB++; } else if (c.GetType()== typeof(TextBox)) { countTB++; } } Response.Write("No of TextBoxes: " + countTB); Response.Write("
"); Response.Write("No of CheckBoxes: " + countCB); }