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);
}
You must recursively loop through other controls.
Just by doing some minor change in the code suggested by Alyafey, pcnThird and Valamas I wrote this code which works.
It allows gives you zero since you are counting the type of your Control control which is not available change your code to :
I believe you have to be recursive,
this.Controls
will only return the controls that are its immediate children. If theTextBox
is within a control group within there, you will need to see the containers controls as well.See the answer to this other stackoverflow: How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?
EDIT: I realize the answer is for WinForms, but the solution still applies.