Is it possible to get a plain text list of controls that are present on a webform using reflection? Basically a colleague is looking to get a list of controls to help define a validation strategy e.g. in general product numbers must be numeric but on certain screens they can be alphanumeric. I thought it would be straightforward using reflection to generate a list of something like:
AddProduct.aspx
txtProductNumber
txtProductName
etc.
I can get the form names but so far not the controls contained within. The current code looks like this:
Assembly assembly = Assembly.LoadFrom(@"Filename.dll");
Type[] types = assembly.GetExportedTypes();
for (int i = 0; i < types.Length; i++)
{
Page page = (Page)assembly.CreateInstance(types[i].FullName);
ControlCollection controls = page.Controls;
// At this point controls.Count = 0 presumably because the controls are defined as protected.
}
Assembly.CreateInstance has a couple of overloads. For example if I change the page assignment line to
Page page = (Page)assembly.CreateInstance(types[i].FullName, true, BindingFlags.NonPublic, null, null, null, null);
then I get an error about a missing constructor.
So have I gone completely down the wrong path or is what I'm attempting to do actually possible at all? Any help is much appreciated.
Edit: Apologies for the delayed response to this question开发者_StackOverflow社区. We got a bit further using Assembly.GetCallingAssembly() to generate a list but it still didn't quite meet our needs. We used a more long-winded Find in Entire solution approach in the end.
Since you are just creating an instance of each page and not actually serving up the pages, I don't believe your approach will work since it will not have the pages go through their normal page request lifecycle that is responsible for creating the page and its child controls.
If this is a single website that uses the asp.net framework controls, you may be better off just doing a "Find in Files" for the tag prefix "
It seems to me that you are looking for controls that are created at runtime. If you want to find these controls at runtime, you can, both with reflection and (depending on the container) with other means. You should do so in the Page_Unload
event, which is where most controls will have been loaded and still available.
But if you are trying to find these controls without processing your pages through the page-request life cycle, it can be daunting. Just creating a page with CreateInstance (or "new") for that matter won't run Page_Load
, Page_Init
or any of the other events. It wil only run the code in the constructor (which, as you found out, is protected, which doesn't mean you cannot instantiate it, but going through that trouble will give you little).
精彩评论