Read, With the Name of Your Lord Who Created

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):

    <%@ Page Language=”C#” %>

    <html>
    <head>
    <title>CSS Inside ASP.NET Server Controls</title>
    <link rel=”stylesheet” type=”text/css” href=”../simple2.css” />
    <script lang=”C#” runat=”server”>
    void ShowText(object sender, EventArgs e)
    {
    this.lbl.Text = this.txtInput.Text;
    }
    </script>
    </head>
    <body>
    <form runat=”server”>
    <asp:TextBox id=”txtInput” CssClass=”TxtStyle” runat=”server” />
    <asp:Button id=”btnSubmit” text=”Submit” onclick=”ShowText” CssClass=”BtnStyle” runat=”server” />
    <p />
    <asp:Label id=”lbl” CssClass=”Common” runat=”server” />
    </form>
    </body>
    </html>

This is external CSS file for the code above (simple2.css):

.BtnStyle
{
   font-family:Times New Roman;
   font-size:20px;
   font-weight:bold;
}

.TxtStyle
{
   font-family:Georgia;
   font-size:17px;
   font-weight:bold;
   border:2px solid goldenrod;
}

.Common
{
   background-color:gainsboro;
   color:red;
   font-family:Courier New;
   font-size:17px;
   font-weight:bold;
}

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):

    <%@ Page Language=”C#” CodeFile=”css_two.aspx.cs” Inherits=”CSS.CSSProgrammatically” %>

    <html>
    <head>
    <title>CSS in ASP.NET</title>
    <link rel=”stylesheet” type=”text/css” href=”../simple2.css” />
    </head>
    <body>
    <form runat=”server”>
    <asp:TextBox id=”txtInput” runat=”server” />
    <asp:Button id=”btnInput” text=”Submit” onclick=”SubmitValue” runat=”server” />
    <p />
    <asp:Label id=”lbl” runat=”server” />
    </form>
    </body>
    </html>

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):

using System;
using System.Web;
using System.Web.UI;

namespace CSS
{
    public partial class CSSProgrammatically : Page
    {
        private void Page_Load()
        {
            this.txtInput.Attributes["class"] = "TxtStyle";
            this.btnInput.Attributes["class"] = "BtnStyle";
            this.lbl.Attributes["class"] = "Common";
        }

        protected void SubmitValue(object sender, EventArgs e)
        {
            this.lbl.Text = this.txtInput.Text;
        }
    }
}

We use the same CSS file as before. The above files will produce output something similar with the previous result.

About these ads

28 Responses to “CSS in ASP.NET Server Controls, Declaratively vs. Programmatically”

  1. satyanarayana said

    hi frnds

  2. SBlangkob said

    Artikel yang bagus, sudah lama pusing cara menghubungkan antara control server dengan CSS, thank’s a lot.

  3. Alba said

    Hi – I stumbled on your site by mistake. I was searching in Yahoo for Georgia vacations for my family trip when I found your site, I have to say your website is pretty cool I just love the theme, its amazing!. I don’t have the time at the moment to totally read your entire site but I have bookmarked it and also will sign up for your RSS feeds. I’ll back in a day or two. Thanks again for a cool site.

  4. Codebuster said

    My word. What good is ASP.NET? It requires so much more lines of code and fiddling with than good ole html and css and maybe a php file for database access.

    It’s just too much for an average site.

    It’s akin to shooting a duck with a battleship! Microsoft has really sold a bill of goods. But, hey, you have a certification, right?

    Simplicity and ease over # of functions anyday.

    • Graham said

      What good is ASP.NET?

      Ha! Over the decade I have been doing web development (both as a primary responsibility and as a “other duties” one), ASP.Net is top dollar. One can very easily and simply produce a website if they wish (as easy as a PHP site, for example). On the other hand, if you need to grow your website into a full function portal, with multiple applications, you can do that too… without switching languages. Having a rich, well documented, set of tools doesn’t mean it isn’t simple. Yes, if you want to leverage some of the most powerful features, you trade simplicity for power, but you (as the developer) can just as easily choose not to make that trade, but I think you will find you can tap a lot of power without giving up the simplicity. ASP.Net is tops simply because you can make the choice of how deep you want to go.

  5. Asif Aziz said

    Me from pakistan.indonations !!!!!!!too nice people

  6. Asif Aziz said

    I love your this sentence “Read, With the Name of Your Lord Who Created”.Me from pakistan. Indonatians!!!!!!!1 too nice people

  7. […] add a CSS Link programmatically using JavaScript How to add CSS Programmatically to an ASP.NET Page CSS in ASP.NET Server Controls, Declaratively vs. Programmatically Programmatically setting the “float” CSS property in Javascript Programmatically […]

  8. Thanks for sharing great information. i hope to every one this site will be help full to read articles to learn new things.

  9. satellite TV info…

    […]CSS in ASP.NET Server Controls, Declaratively vs. Programmatically « Read, With the Name of Your Lord Who Created[…]…

  10. Informasi Online Organisasi Warga Jawa Keluyuran di Sumatera…

    […]CSS in ASP.NET Server Controls, Declaratively vs. Programmatically « Read, With the Name of Your Lord Who Created[…]…

  11. bal intermobil…

    […]CSS in ASP.NET Server Controls, Declaratively vs. Programmatically « Read, With the Name of Your Lord Who Created[…]…

  12. go to my pc login…

    […]CSS in ASP.NET Server Controls, Declaratively vs. Programmatically « Read, With the Name of Your Lord Who Created[…]…

  13. Proxy Server…

    […]CSS in ASP.NET Server Controls, Declaratively vs. Programmatically « Read, With the Name of Your Lord Who Created[…]…

  14. anwar said

    Very fine topic

  15. Trina said

    whoah this blog is fantastic i like studying your
    posts. Keep up the good work! You already know, many individuals are searching
    around for this information, you can aid
    them greatly.

  16. Belen said

    Hmm is anyone else encountering problems with the pictures on this blog
    loading? I’m trying to determine if its a problem on my end or if it’s the blog.
    Any suggestions would be greatly appreciated.

  17. Maik said

    Great blog you have here but I was wondering if you knew of any user discussion forums that
    cover the same topics discussed in this article? I’d really like to be a part of group where I can get advice from other experienced people that share the same interest. If you have any recommendations, please let me know. Thanks!

  18. Hi I am so glad I found your web site, I really found you
    by mistake, while I was looking on Google for something else, Nonetheless I am here now and would just like to say thanks
    for a remarkable post and a all round enjoyable blog (I also love the theme/design),
    I don’t have time to read it all at the minute
    but I have saved it and also added your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the awesome b.

  19. Nice respond in return of this issue with real
    arguments and telling the whole thing on the topic of that.

  20. Cathern said

    I don’t know whether it’s just me or if perhaps everybody else
    experiencing issues with your site. It appears as if some of the
    text on your content are running off the screen.
    Can somebody else please provide feedback and let me know if this is happening to them as well?
    This could be a issue with my browser because I’ve had this happen previously. Many thanks

  21. Dominique said

    Both drugs have also been denied FDA approval the first time around and are awaiting news on their second attempt.
    Withdrawal from levothyroxine can be done but it takes 6 weeks of withdrawal for
    the remaining thyroid tissue to be completely starved.
    Many people don’t have the time to weight themselves every day, but checking the scale on a regular basis can definitely help when you’re working
    to lose weight and keep it off.

  22. a Bruce Lee workout includes stretching, bending, running, dipping, kicking, jumping, traditional muscle building exercises, weight lifting,
    rope skipping, medicine ball handling, etc. Vitamin B3 or also called as Niacin is important in
    weight loss because it is responsible for the regulation of thyroid hormones and also in sugar levels in the body.
    Who does not need that little bit of elevation when trying to diet.

  23. Would you like to save money by not hiring a wedding planner, but
    you feel overwhelmed by the thought of trying to organize, track and complete all the details and tasks by yourself.
    For instance, it is an excellent idea to prepare the birthday cake of a golf
    lover in the shape of a golf ball in a golf course.
    On the other hand, if you are a retailer who sells appropriate gifts
    such as jewelry and perfumes or have a romantic restaurant you can customize these certificates and sell them to patrons.

  24. Sherri said

    You don’t have to hit the gym for two and three hours each day to lose weight, but it does help to squeeze in 30 minutes of physical activity each day. Vinson had participants keep their normal diet and exercise routines (or lack thereof) and merely added the green coffee. The institution has persistently offered ideal programs and services for those struggling to achieve certain levels of body weight.

  25. Victoria said

    a Bruce Lee workout includes stretching, bending, running, dipping, kicking, jumping, traditional muscle building exercises, weight lifting, rope skipping, medicine ball handling,
    etc. Anyone who dares to make a closer inspection will find the
    underlying difference. Many people don’t have the time to weight themselves every day, but checking the scale on a regular basis can definitely help when you’re working to lose weight and keep it off.

  26. Hi! This post could not be written any better!
    Reading this post reminds me of my good old room mate!
    He always kept talking about this. I will forward
    this page to him. Pretty sure he will have a
    good read. Thank you for sharing!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: