gpt4 book ai didi

c# - 计算表单中 TextBoxes 和 CheckBoxes 的数量

转载 作者:行者123 更新时间:2023-11-30 20:01:56 26 4
gpt4 key购买 nike

我的要求是在用户点击按钮'btnGetCount'。这是我尝试过的代码,但它不计算任何内容并且计数器保持为零,尽管我在表单中有三个 TextBoxes 和两个 CheckBoxes。但是,如果我删除 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("<br>");
Response.Write("No of CheckBoxes: " + countCB);
}

最佳答案

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

    <form id="form1" runat="server">
<div>
<asp:TextBox ID="txt" runat="server"></asp:TextBox>
<asp:CheckBox ID="cb" runat="server"></asp:CheckBox>
</div>
</form>

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

关于c# - 计算表单中 TextBoxes 和 CheckBoxes 的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17712051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com