I have a Web content form and need to access a control inside the content panel. I know of two ways to access the control:
TextBox txt = (TextBox)Page.Controls[0].Controls[3].Controls[48].Controls[6]
- By writing a recursive function that searches through all controls.
Is there any other easier way, since Page.FindControl
doesn’t work in this instance.
The reason I am asking is it feels to me like the Page object or the Content Panel object should have a method to find a child control, but can’t find anything like it.
I would like to change your
GetControls
function to a generic one as follows:And Then,
This way, the caller would call something like:
The issue is that FindControl() does not traverse certain control children such as a templated control. If the control you are after lives in a template, it won't be found.
So we added the following extension methods to deal with this. If you are not using 3.5 or want to avoid the extension methods, you could make a general purpose library out of these.
You can now get the control you are after by coding:
The extension methods do the recursive work for you. Hope this helps!