Search code examples
c#asp.netreflectionasp.net-webcontrol

how to read value of style["display"] property of webcontrol using reflection


I have some user controls and some web controls on my page. To read the Visibility property of the each control using reflection I wrote below line :

Object v;
if (control.GetType().GetProperty("Visible") != null)
     v = control.GetType().GetProperty("Visible").GetValue(control, null);

but how can I read the value of Style["display"] attribute of each control using reflection?

Thanks in advance.


Solution

  • Here is a working example using a button for demonstration purposes only.

    Style property with the attribute as a key we are looking for must be applied to it.

    Markup:

    <asp:Button ID="Button1" runat="server" Text="Button" Visible="false" style="display:block;" />
    

    Code behind:

    var styleProp = Button1.GetType().GetProperty("Style");
            if (styleProp != null)
                {
                    var styleCollection = styleProp.GetValue(Button1, null) as CssStyleCollection;
                    var value = styleCollection["display"];
                }
    

    You would have to replace the button with which ever control you have already.