Blog Home  Home Feed your aggregator (RSS 2.0)  
Applying a Style to an HtmlControl - Manuel Abadia's ASP.NET stuff
 
# Wednesday, 24 May 2006

I was giving the final touches to a control I was developing and I found out that I couldn’t apply a Style object to an HtmlControl directly. An HtmlControl exposes a Style property of type CssStyleCollection and the WebControl exposes a ControlStyle property of type Style. My control has several properties of type Style and I had styled WebControls without any problem using the ApplyStyle method, but that was not possible with HtmlControls.

To solve the problem you have the option to use only WebControls instead of HtmlControls and produce the same Html output but that was my last option.

I searched google but I only found a helper class that did the translation:

http://www.cambiaresearch.com/cambia3/snippets/csharp/classes/StyleHelper.aspx

Fortunately there's a way to avoid having to do that conversion “manually”. This is the method that I’m using now to style a control:

public void ApplyStyleToControl(Control control, Style style)

        {

            // if the control is a WebControl, apply the style directly

            if (control is WebControl) {

                ((WebControl)control).ApplyStyle(style);

            } else if (control is HtmlControl) {

                // if the control is a HtmlControl

                HtmlControl htmlControl = (HtmlControl)control;

 

                // get the css style collection from the style and modify the control's style collection

                CssStyleCollection styles = style.GetStyleAttributes(control);

                foreach (string key in styles.Keys) {

                    htmlControl.Style[key] = styles[key];

                }

            }

        }


The GetStyleAttributes is not present in version 1.x so if you’re not using version 2.0 you’re out of luck!

Wednesday, 24 May 2006 19:44:02 (Romance Daylight Time, UTC+02:00)  #    Comments [0]   ASP.NET  | 
Copyright © 2018 Manuel Abadia. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.