繁体   English   中英

根据C#中的条件列出控件的所有属性名称

[英]list all property names of controls based on condition in C#

我试图从某个页面(this.Page.Controls)解析所有控件的所有属性(例如ascx文件),以获得具有我指定的属性值的属性的名称,例如-值为“这是我的标头”的属性的名称是什么? (很可能是一个包含此值的文本框)。

以下返回此错误:

无法获得内部内容,因为内容不是文字的。 System.Web.UI.HtmlControls.HtmlContainerControl.get_InnerHtml()

不知道这意味着什么或如何纠正它。

 public String searchMethod(List<Control> listOfControls, String searchedValue)
        {
            String result = "";

            foreach (var control in listOfControls)
            {
                PropertyInfo[] properties = control.GetType().GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if (property.PropertyType == typeof (string)) //added condition on this line *******************************
                    {
                        if (property.GetValue(control, null) != null)
                            if (property.GetValue(control, null).ToString().Contains("searched String"))
                            {
                                result = result + property.Name + "/" + property.GetValue(control, null) + "/";
                            }
                    }

                }
            }
            return result;
        }

我想它卡在一个不符合要求的属性上,那么为什么不简单地将其移至下一个,直到找到合适的位置? 显然,卡住的属性是System.String Inner.Html

PS。 我已经测试了馈给该方法的listOfControls,并且它已正确生成

以后的更新:我尝试的另一种方法是:

public string Method1(List<Control> controlList, string propName)
        {
            string result = "";
            foreach (var control in controlList)
            {
                foreach(var prop in control.GetType().GetProperties())
                {
                    if(prop.PropertyType == typeof(string))
                    {
                        if((prop.GetValue(control,null).GetType()) == typeof(string))
                            if (prop.GetValue(control, null).ToString().Contains(propName))
                        result += prop.Name + "######";
                    }
                }
            }
            return result;
        }

但是与此有关,我得到的对象引用未设置为对象的实例。 在线if((prop.GetValue(control,null).GetType()) == typeof(string))

这是HtmlContainerControl.InnerHtml的已记录行为-在“例外”部分中,如果发生以下情况,它将抛出HttpException

有多个HTML服务器控件。
- 要么 -
HTML服务器控件不是System.Web.UI.LiteralControl或System.Web.UI.DataBoundLiteralControl。

听起来您的情况正在发生后一种情况。 该代码不会“继续前进”,因为正在引发但未捕获到异常。

老实说,我建议您对检查的控件类型有所挑剔,并且我可能会使用特定的属性,而不仅仅是调用ToString()

如果控件中包含控件,则会收到该错误。 您是否需要搜索列表中控件内部的控件? 如果是这样,您将需要使用递归并继续深入到控件(及其中的任何控件),并且仅在不包含其他控件的控件上检查InnerHtml

您还可以通过仅在property.PropertyType == typeof(string)时检查值来稍微简化一下。 你也可以将搜索范围限制只是两个属性- TextInnerHtml ,如果这是适用的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM