代码之家  ›  专栏  ›  技术社区  ›  DraÅ¡ko

如何在asp.net中从字符串中获取控件的属性值

  •  1
  • DraÅ¡ko  · 技术社区  · 15 年前

    我需要循环通过ASP.NET网页上的所有控件。在配置文件中,我有一个控件类型及其属性的列表,我将以某种方式处理它们。现在,我感兴趣的是:当我只有字符串时,如何获得所需的属性,即控件类型的名称及其各自属性的名称。

    controltype = "label" propertyname = "Text"  
    controltype = "Image" propertyname = "ToolTip".
    

    所以我的代码里有这样的东西:

    List<Control> controls = GiveMeControls();  
    foreach(Control control in controls)  
    {  
        // in getPropertyNameFromConfig(control) I get typename of control   
        // and returns corresponding property name  from config type
        string propertyName = getPropertyNameFromConfig(control);    
        string propertyValue = getPropertyValueFromProperty(control, propertyValue);
        // !!! Don't      know how to write getPropertyValueFromProperty.  
    }  
    

    有人知道如何开发getPropertyValueFromProperty()吗?

    提前谢谢,

    2 回复  |  直到 15 年前
        1
  •  2
  •   Timwi    15 年前

        static string getPropertyValueFromProperty(object control, string propertyName)
        {
            var controlType = control.GetType();
            var property = controlType.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (property == null)
                throw new InvalidOperationException(string.Format("Property “{0}” does not exist in type “{1}”.", propertyName, controlType.FullName));
            if (property.PropertyType != typeof(string))
                throw new InvalidOperationException(string.Format("Property “{0}” in type “{1}” does not have the type “string”.", propertyName, controlType.FullName));
            return (string) property.GetValue(control, null);
        }
    

    如果你有任何关于这个工作原理的问题,请随时发表评论。

        2
  •  1
  •   Peter Lillevold Rene    15 年前

    您必须使用反射API。用它你可以检查类型和 locate the properties by name ,然后使用属性从控件实例获取值。