Skip to content

Dynamically adding Style Sheet Reference in ASP.Net

In ASP.Net, many times there are scenarios when you want to add a style sheet (CSS) reference to your page from the code behind. Usually, we can do a line (example below) in the page and we are done.

<LINK REL='StyleSheet' HREF='manas.css' TYPE='text/css'>

To do something like this from codebehind, you can use the snippet below.

public void AddHeaderStyleSheetReference(Page PageObject, string StyleSheetURL)
	if (PobjPage.Header != null)
		HtmlGenericControl StyleSheet = new HtmlGenericControl("Link");
		LobjStyleSheet.Attributes.Add("Rel", "StyleSheet");
		LobjStyleSheet.Attributes.Add("Type", "text/css");
		LobjStyleSheet.Attributes.Add("HRef", PageObject.ResolveClientUrl(StyleSheetURL));

A similar approach can be made to add the JavaScript file references to you page.

public void AddHeaderScriptReference(Page PageObject, string ScriptURL)
	if (PageObject.Header != null)
		HtmlGenericControl IncludeScript = new HtmlGenericControl("Script");
		LobjIncludeScript.Attributes.Add("Type", "JavaScript");
		LobjIncludeScript.Attributes.Add("CharSet", "UTF8");
		LobjIncludeScript.Attributes.Add("Src", PageObject.ResolveClientUrl(ScriptURL));
Published inUncategorized

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *