CSS in ASP.NET Server Controls, Declaratively vs. Programmatically
Posted by triaslama on May 7, 2008
ASP.NET controls has a bunch of attributes that take in order the look and feel of every control. For example TextBox server control, if we want the TextBox color turn into specific color we specify the ForeColor attribute to the name of Color defined in Color structure. If we want the TextBox text font appear in Georgia font, set Font-Name attribute to Georgia. ASP.NET TextBox script for above requirements will look something like this:
<asp:TextBox id="txtTest" ForeColor="Red" Font-Name="Georgia" runat="server" />
It looks simple, right?
But wait, for the one familiar with ASP.NET it doesn’t matter, but for everyone who already familiar with CSS maybe there is a bit problem because the attribute name of ASP.NET server controls slightly different with attribute in CSS file. So sometimes we may prefer that the looks and feels of ASP.NET controls ruled within CSS file. And yes, we can do this!
In ASP.NET information within a CSS file can be accessed either declaratively or programmatically, its up to you which one to choose. To make a CSS file visible within our page put this declaration inside our <head></head> tag:
<link rel="stylesheet" type="text/css" href="[filelocation/css_filename.css]" />
Accessing CSS Declaratively in ASP.NET Server Controls
To access CSS file in declaratively style, we need CssClass attribute of every ASP.NET server control. We pass class inside CSS file as value for CssClass attribute. Look at the following code for detail (css_one.aspx):
This is external CSS file for the code above (simple2.css):
This is the result of css_one.aspx:
Style of ASP.NET page via CSS.
Accessing CSS Programmatically in ASP.NET Server Controls
Accessing CSS programmatically can be accomplised with the help of Attributes property of ASP.NET server controls. For example if we want apply styles defined in external CSS file in Button object named btn:
btn.Attributes["class"] = "BtnStyle";
The rest should be same as declaratively manner, but I use code behind and put the C# code in separate file (css_two.aspx.cs). This is our presentation (css_two.aspx):
In Page directive we add CodeFile and Inherits attributes, because we use code behind in css_two.aspx.cs file and our page will use partial class defined in CSS.CSSProgrammatically class. This class resides in css_two.aspx.cs file. This is the code behind (css_two.aspx.cs):
We use the same CSS file as before. The above files will produce output something similar with the previous result.