Count the number of TextBoxes and CheckBoxes in a form

14,339

Solution 1

You must recursively loop through other controls.

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

Solution 2

It allows gives you zero since you are counting the type of your Control control which is not available change your code to :

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("<br>");
        Response.Write("No of CheckBoxes: " + countCB);
    } 
Share:
14,339
RahulD
Author by

RahulD

Student of Computer Science.

Updated on June 05, 2022

Comments

  • RahulD
    RahulD almost 2 years

    My requirement is to count the total number of TextBox and CheckBox present directly inside the form with the id="form1", when the user clicks on the Button 'btnGetCount'. Here is the code which I have tried but it doesn't count anything and counter remains at zero, though I have three TextBoxes and two CheckBoxes in the form. However, if I remove foreach loop and pass TextBox control = new TextBox(); instead of the present code then it counts the first TextBox and countTB returns the value as one.

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