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