Home > Articles > Programming > ASP .NET

Customizing and Managing Your Site's Appearance with ASP.NET 2.0 Tools

ASP.NET 2.0 provides a number of ways to customize the style of pages and controls in your Web application. This chapter covers these approaches. It examines the various appearance properties of Web server controls, illustrates how to use CSS with ASP.NET, moves on to themes and master pages, and then finishes with user controls.
This chapter is from the book

Changing the Appearance of Server Controls

The previous chapters introduced many of the standard Web server controls. This section returns to the coverage of Web server controls by demonstrating how to more fully customize the appearance of these controls. The chapter does so in two ways. The first way uses common formatting properties of the Web server controls, whereas the second way uses cascading style sheets.

Using Common Appearance Properties

As mentioned back in Chapter 3, most of the standard Web server controls inherit from the WebControl class. This WebControl class in turn inherits from the Control class. Both of these base classes define properties that can be used to modify the appearance of any Web server control. Table 6.1 lists the principal appearance properties of the WebControl and Control classes.

Table 6.1. Appearance Properties of the WebControl and Control Classes

Property

Description

BackColor

The background color (using either a hexadecimal HTML color identifier or a standardized color name) of the control.

BorderColor

The color of the control's border.

BorderWidth

The thickness (in pixels) of the control's border.

BorderStyle

The style (e.g., dotted, dashed, solid, double, etc.) of the control's border. Possible values are described by the BorderStyle enumeration.

CssClass

The CSS class name assigned to the control.

Enabled

Toggles the functionality of the control; if set to false, the control is disabled.

Font

List of font names for the control.

ForeColor

The color of the text of the control.

Height

The height of the control.

Style

A collection of attributes that is rendered as an HTML style attribute.

Visible

Specifies whether the control is visible.

Width

The width of the control.

Any of the properties listed in Table 6.1 can be set declaratively or programmatically. For instance, the following markup demonstrates how to set the foreground and the background colors of a Label control.

<asp:Label id="labTest" runat="server"
   ForeColor="#CC33CC" BackColor="Blue"/>

To set the same properties programmatically, you could do so in a number of different ways, two of which are shown here.

labTest.ForeColor = Color.FromName("#CC33CC");
labTest.BackColor = Color.Blue;

Color is a C# struct that has fields for the predefined color names supported by the major browsers, as well as methods for creating a Color object from a name or from three numbers representing RGB values.

Most of the various appearance properties are rendered in the browser as inline CSS styles. For instance, the Label control from the preceding two examples would be rendered to the browser as

<span id="labTest" style="color:#CC33CC;
   
   background-color:Blue;"></span>

Using the Style Class

Setting the various formatting properties for your Web controls, whether through programming or declarative means, is acceptable when there are only one or two properties to set. However, when you have many properties that need to be changed in multiple controls, this approach is not very ideal. A better approach is to use the Style class.

The Style class is ideal for changing multiple properties to multiple controls all at once. It encapsulates most of the formatting properties listed in Table 6.1 and can be applied to multiple Web server controls to provide a common appearance. To use this class, you simply instantiate a Style object, set its various formatting properties, and then apply the style to any server control by using the control's ApplyStyle method. The following example illustrates this usage.

Style myStyle = new Style();
myStyle.ForeColor = Color.Green;
myStyle.Font.Name = "Arial";

// Now apply the styles to the controls
myLabel.ApplyStyle(myStyle);
myTextBox.ApplyStyle(myStyle);

The Style class is best for situations where you need to programmatically change the appearance of a set of controls all at once. If you simply need to set up a consistent appearance to a series of controls, it is almost always better to use Cascading Style Sheets (CSS) or ASP.NET themes, both of which are covered in this chapter.

Using CSS with Controls

The previous section demonstrated how to use some of the common appearance properties of Web server controls. Although these properties are very useful for customizing the appearance of your Web output, they do not contain the full formatting power of Cascading Style Sheets. Fortunately, you can also customize the appearance of Web server controls using CSS.

There are two ways to harness the power of CSS with Web server controls. The first way is to assign a CSS declaration to the Style attribute/property of a control. For instance, the following example sets the CSS letter-spacing property to increase the whitespace between each letter in the Label to 2 pixels, along with setting the font style to italic.

<asp:label id="labMsg" runat="server" Text="hello world"
   style="letter-spacing: 2px; font-style: italic" />

To achieve the same effect by programming, you would use

labMsg.Style["letter-spacing"] = "2px";
labMsg.Style["font-style"] = "italic";

Notice that from a programming perspective, the Style property is a named collection. A named collection acts like an array, except that individual items can be retrieved either through a zero-based index or a unique name identifier.

All styles added to a control, whether declaratively or programmatically, are rendered in the browser as an inline CSS rule. For instance, either of the two previous two examples would be rendered to the browser as

<span id="labMsg" style="letter-spacing:2px;font-style: italic">
hello world
</span>

The other way to use CSS with Web server controls is to assign a CSS class to the CssClass property of a control. For instance, assume that you have the following embedded CSS class definition.

<style type="text/css">
   .pullQuote { background: silver;
               margin: 10px;
               font-family: Verdana, Arial,Helvetica,sans-serif;
               font-size: 10pt; }
</style>

You could assign this CSS class via

<asp:label id="labMsg2" runat="server" CssClass="pullQuote" />

To achieve the same effect by coding, you would use

labMsg2.CssClass = "pullQuote";

Listings 6.1 and 6.2 demonstrate how to style Web server controls with CSS by using both the Style and CssClass properties. The markup contains three Label controls, each of which contain a paragraph of text. The form also contains two DropDownList controls. The first changes the CSS text-transform property (which changes the text from uppercase to lowercase) for two of the Label controls. The second DropDownList control sets the other Label control's CssClass property to one of two predefined CSS classes, both of which float the paragraph so that it becomes a pull quote relative to the other text (see Figure 6.1).

Figure 6.1

Figure 6.1 Using CSS.aspx

Although the example in Listing 6.1 uses embedded styles (that is, CSS rules within an HTML <style> element), you should generally locate a page's CSS in an external file and then link to it using the <link> element. By doing so, multiple pages in the site can use the same CSS file. As well, using an external CSS file generally reduces the page's bandwidth, because the browser can cache the CSS file.

Listing 6.1. Using CSS.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Using CSS</title>
   <style type="text/css">
      body {
         background: #fffafa; margin: 1em;
         font: small/1.5em verdana, arial, sans-serif;
      }
      h1 {
         background: gold; color: black;
         font: bold 120% verdana, helvetica, sans-serif;
         letter-spacing: 0.25em; padding: 0.25em;
      }
      .controlPanel {
         padding: 0.5em; border: black 1px solid;
         background: #eee8a; margin: 1.5em; width: 75%;
      }
      .pullQuoteOne {
         padding: 0.25em; margin: 0.25em 1em;
         border: solid 7px #908070;
         border-right-width: 0; border-left-width: 0;
         background: lightgrey;
         float: right; width: 15em;
         font: bold 90% arial, helvetica, verdana, sans-serif;
      }

      .pullQuoteTwo {
         padding: 0.25em; margin: 1.5em;
         border: #82a91b 2px solid;
         background: #adc175;
         float: left; width: 10em;
         font: bold 105% times new roman, serif;
      }
   </style>
</head>
<body>
   <form id="form1" runat="server">
      <h1>Using Styles</h1>
      <p>
      <asp:Label ID="labOne" runat="server">
      The previous section demonstrated how to use some of the common
display properties of web server controls. While these properties are
very useful for customizing the appearance of your web output, they
do not contain the full formatting power of Cascading Style Sheets
(CSS).
      </asp:Label>
      </p>
      <p>
      <asp:Label ID="labPullQuote" runat="server">
      Luckily, you can also customize the appearance of web
      server controls using CSS.
      </asp:Label>
      </p>
      <p>
      <asp:Label ID="labTwo" runat="server">
      There are two ways to harness the power of CSS with web server
controls. The first way is to assign a CSS declaration to the Style
attribute/property of a control. For instance, the following example
sets the CSS letter-spacing property to set the white space between
each letter in the Label to 2 pixels, and the font style to italics.
The other way to use CSS with web server controls is to assign a CSS
class to the CssClass property of a control.
      </asp:Label>
      </p>

      <div class="controlPanel">
         <p>Modify styles using drop-down lists below:</p>
         <p>Paragraph Text text-transform style:
         <asp:DropDownList ID="drpParagraph" runat="server"
               AutoPostBack="True" OnSelectedIndexChanged=
               "drpParagraph_SelectedIndexChanged">
            <asp:ListItem Selected="True">
            Choose a text-transform style</asp:ListItem>
            <asp:ListItem Value="lowercase">
               lowercase</asp:ListItem>
            <asp:ListItem Value="uppercase">
               uppercase</asp:ListItem>
            <asp:ListItem Value="capitalize">
               capitalize</asp:ListItem>
         </asp:DropDownList>
         </p>
         <p>Pull Quote CSS class:
         <asp:DropDownList ID="drpPull" runat="server"
               AutoPostBack="True" OnSelectedIndexChanged=
               "drpPull_SelectedIndexChanged">
            <asp:ListItem Selected="True">
               Choose a css class</asp:ListItem>
            <asp:ListItem Value="pullQuoteOne">
               pullQuoteOne</asp:ListItem>
            <asp:ListItem Value="pullQuoteTwo">
               pullQuoteTwo</asp:ListItem>
         </asp:DropDownList>
         </p>
      </div>
   </form>
</body>
</html>

The code-behind class (shown in Listing 6.2) for this example is quite straightforward. It contains selection event handlers for the two DropDownList controls. The first of these changes the text-transform CSS property of two Label controls based on the user's selection; the second sets the CSS class of the pull quote Label based on the user's selection.

Listing 6.2. Using CSS.aspx.cs

public partial class UsingCSS : System.Web.UI.Page
{
   /// <summary>
   /// Handler for text transform drop-down list
   /// </summary>
   protected void drpParagraph_SelectedIndexChanged(
         object sender, EventArgs e)
   {
      if (drpParagraph.SelectedIndex > 0)
      {
         labOne.Style["text-transform"] =
            drpParagraph.SelectedValue;
         labTwo.Style["text-transform"] =
            drpParagraph.SelectedValue;
      }
   }
   /// <summary>
   /// Handler for pull quote drop-down list
   /// </summary>
   protected void drpPull_SelectedIndexChanged(object sender,
         EventArgs e)
   {
      if (drpPull.SelectedIndex > 0)
         labPullQuote.CssClass = drpPull.SelectedValue;
   }
}

Appearance Properties, CSS, and ASP.NET

The intent of CSS is to separate the visual presentation details from the structured content of the HTML. Unfortunately, many ASP.NET authors do not fully take advantage of CSS, and instead litter their Web server controls with numerous appearance property settings (e.g., BackColor, BorderColor, etc.). Although it is true that these properties are rendered as inline CSS styles, the use of these properties still eliminates the principal benefit of CSS: the capability to centralize all appearance information for the Web page or Web site into one location, namely, an external CSS file. Also, because the appearance properties are rendered as inline CSS, this increases the size and the download time of the rendered page.

By limiting the use of appearance properties for Web server controls within your Web Forms, and using instead an external CSS file to contain all the site's styling, your Web Form's markup becomes simpler and easier to modify and maintain. For instance, rather than setting the Font property declaratively for a dozen Web server controls in a page to the identical value, it makes much more sense to do so via a single CSS rule. And if this CSS rule is contained in an external CSS file, it could be used throughout the site (that is, in multiple Web Forms), reducing the overall amount of markup in the site.

However, ASP.NET 2.0 does provide an additional mechanism for centralizing the setting the appearance of Web server controls on a site-wide basis, called themes and skins, which is our next topic.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020