获取程序集中每个WebForm上的控件列表

获取程序集中每个WebForm上的控件列表

本文介绍了获取程序集中每个WebForm上的控件列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用反射获取Web窗体上存在的控件的纯文本列表?基本上,一位同事正在寻求获取控件列表以帮助定义验证策略,例如通常,产品编号必须是数字,但在某些屏幕上,它们可以是字母数字.我认为使用反射生成类似以下内容的列表将很简单:

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 有一些重载.例如,如果我将页面分配行更改为

Assembly.CreateInstance has a couple of overloads. For example if I change the page assignment line to

然后我收到关于缺少构造函数的错误.

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.

编辑:对于对此问题的延迟答复表示歉意.我们进一步使用Assembly.GetCallingAssembly()生成了一个列表,但是它仍然不能完全满足我们的需求.最终,我们使用了更为冗长的在整个结果中查找"解决方案.

Apologies for the delayed response to this question. 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.

这篇关于获取程序集中每个WebForm上的控件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:23