I have a page that has 5 user controls. I want to do more with them, but for now, I just want to count them using the following method.
void btnFormSave_Click(object sender, EventArgs e)
{
int i = 0;
ControlCollection collection = Page.Controls;
foreach (Control ctr in collection)
{
if (ctr is UserControl)
{
i++;
}
}
}
When I debug this code, i = 1, and the control is the master page (I didn't know that the master page is a user control).
How do I count user controls that are on my page?
This is my content placeholder markup.
<asp:Content ID="cntMain" runat="Server" ContentPlaceHolderID="ContentMain">
You only need to change where you look for:
void btnFormSave_Click(object sender, EventArgs e)
{
int i = 0;
// here, look inside the form, and not on page.
ControlCollection collection = Page.Form.Controls;
foreach (Control ctr in collection)
{
if (ctr is UserControl)
{
i++;
}
}
}
I have tested and working for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With