Get a list of controls in each web form in the assembly

Can I get a simple text list of controls that are present on a web form using reflection? Basically, a colleague wants a list of controls to help determine a validation strategy, for example. in general, product numbers must be numeric, but on some screens they may be alphanumeric. I thought that using reflection would be easy to create a list of something like:

AddProduct.aspx txtProductNumber txtProductName etc. 

I can get the names of the forms, but still did not contain the controls. 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’s destination string to

Page of page = (Page) assembly.CreateInstance (types [i] .FullName, true, BindingFlags.NonPublic, null, null, null, null);

then I get an error with a missing constructor.

So, am I completely off the wrong track or am I even trying to do this at all? Any help is greatly appreciated.

Edit: Sorry for the delay in answering this question. We got a bit more using Assembly.GetCallingAssembly () to create a list, but it still didn't quite fit our needs. In the end, we used the longer Find in Target approach.

0
source share
2 answers

Since you simply create an instance of each page and don't actually serve the pages, I don’t think your approach will work, because it will not have pages going through their normal page request life cycle, which is responsible for creating and its child controls.

If this is one website that uses the asp.net framework controls, you might be better off just doing a “File Search” to prefix the tag “

+2
source

It seems to me that you are looking for controls created at runtime. If you want to find these controls at runtime, you can either with reflection, or (depending on the container) with other means. You must do this in the Page_Unload event, where most of the controls will be loaded and still available.

But if you try to find these controls without processing your pages through the page request life cycle, this can be tricky. Just creating a page using CreateInstance (or "new") will not fire Page_Load , Page_Init or any other event. It will run only the code in the constructor (which, as it turned out, is protected, which does not mean that you cannot create it, but through this problem you will not be difficult).

+1
source

Source: https://habr.com/ru/post/928071/


All Articles