Introduction
Recently, when I was working on the ASP.NET web site, I wanted to modify the page styles dynamically. I Googled and found that there are various techniques out there for this. In this tip, I wish to share those techniques with you.
Using the Code
Following are some of the techniques out there to accomplish this.
1. By using Page.header.Controls.Add()
Page.Header
property gets the document header of the page if the head
element is defined with “runat=server
” tag in the page declaration.The Header
property gets a reference to an HtmlHead
object that you can use to set document header information for the page. The HtmlHead
allows you to add information such as style sheets, style rules, a title, and metadata to the head
element.
You can read more about Page.Header
property here.
By using a literal control, you can include the CSS file or even a style set.
Literal cssFile = new Literal()
{
Text = @"<link href=""" + Page.ResolveUrl(styleFilePath) +
@""" type=""text/css"" rel=""stylesheet""/>"
};
Page.Header.Controls.Add(cssFile);
Page.Header.Controls.Add(
new LiteralControl(
@"<style type='text/css'>
.myCssClass
{
background: black;
border: 1px solid;
}
</style>
"
));
Or HtmlGenericControl
can use to add the styles file:
HtmlGenericControl oCSS = oCSS = newHtmlGenericControl();
oCSS.TagName = "link";
oCSS.Attributes.Add("href", "css/mystyle.css");
oCSS.Attributes.Add("rel", "stylesheet");
oCSS.Attributes.Add("type", "text/css");
this.Page.Header.Controls.Add(oCSS);
2. Page.Header.Stylesheet
A more elegant technique is the use of the Page.Header.Stylesheet
. Instead of using the string
to defend styles (like above with Literal), you can use the style
properties to create this.
Style dynamicClassStyle = new Style();
dynamicClassStyle.BorderStyle = BorderStyle.Solid;
dynamicClassStyle.BorderColor = System.Drawing.Color.Black;
dynamicClassStyle.BorderWidth = new Unit(1);
dynamicClassStyle.BackColor = System.Drawing.Color.White;
Page.Header.StyleSheet.CreateStyleRule(dynamicClassStyle, null, ".MyCssClass");
Style dynamicTypeStyle = new Style();
dynamicTypeStyle.BorderStyle = BorderStyle.Solid;
dynamicTypeStyle.BorderColor = System.Drawing.Color.Black;
dynamicTypeStyle.BorderWidth = new Unit(1);
dynamicTypeStyle.BackColor = System.Drawing.Color.White;
Page.Header.StyleSheet.CreateStyleRule(dynamicTypeStyle, null, "DIV");
For more information, please refer to this link.
With whatever technique you follow, please remember the following hints as well,
Adding styles programmatically using the methods of the IStyleSheet
interface during asynchronous postbacks is not supported. When you add AJAX capabilities to a Web page, asynchronous postbacks update regions of the page without updating the whole page.