Decrease Font Size
Increase Font Size

ASP.NET load Stylesheet dynamically with no duplicate

ASP.NET load Stylesheet dynamically |

How to load CSS for page dynamically |

Dynamically loading a CSS file |

Dynamically add link to CSS Stylesheet? |

ASP.NET load Stylesheet dynamically with no duplicate


I have an ASP.NET WebUserControl that requires a CSS Stylesheet to display correctly. My goal is to not include the CSS stylesheet in any of my Page or Masterpage whenever I consume the WebUserControl. All I want to do is just drag and drop one or more of the WebUserControl on to my page and I'm good to go. I can solve this maze by loading the CSS stylesheet in my user WebUserControl dynamically. But it will load duplicates CSS on my page if I have more than one of the identical WebUserControl. If you happen to come across into this kind of situation, here is the solution on how to prevent loading duplicate CSS stylesheet on your page. It works for me, comments are welcome.

Use this code in the WebUserControl

protected void Page_Load(object sender, EventArgs e)

//load style css
    internal void LoadCss()
        //prevent loading multiple css style sheet
        HtmlControl css = null;
        if (Session["MultipleSelectionDDLCSSID"] != null)
            css = Page.Header.FindControl(Session["MultipleSelectionDDLCSSID"] as string) as HtmlControl;
        if (css == null)
            //load the style sheet
            HtmlLink cssLink = new HtmlLink();
            cssLink.ID = "MultipleSelectionDDLCSSID";
            cssLink.Href = "StyleSheet.css";
            cssLink.Attributes.Add("rel", "stylesheet");
            cssLink.Attributes.Add("type", "text/css");

            // Add the HtmlLink to the Head section of the page.

            Session["MultipleSelectionDDLCSSID"] = cssLink.ID;

Comments (5) -

  • latina women

    8/14/2009 11:43:47 PM |

    Great article. Where else could anyone get that kind of information in such a perfect way of presentation.

  • bad credit personal loans

    1/4/2010 7:44:23 PM |

    Positive thinking won't let you do anything but it will let you do everything better than negative thinking will.

  • online payday loans

    1/8/2010 6:05:53 AM |

    Each friend represents a world in us, a world possibly not born until they arrive, and it's only by this meeting that a new world is born.

  • research paper

    3/6/2010 11:52:21 PM |

    Let stay positive in every single day.

  • ollie

    6/6/2010 1:04:58 PM |

    I really like your blog about stylesheet Smile  This is my second visit to your site and I think I might just have to subscribe, thanks for posting about stylesheet . Peace.

Pingbacks and trackbacks (4)+

Add comment