Style Properties

For the most part, ASP.NET scripts are information processors. They take data values input by users or extracted from files and databases and convert that data to information through processing routines. At the same time, scripts can arrange and style the output for differing visual effects. They can produce XHTML code for delivery to the browser, and they can style the information for dramatic effect.

Changing the style characteristics of HTML elements on-the-fly is familiar to those who have worked with Dynamic HTML. DHTML is a browser phenomenon, using Cascading Style Sheets (CSS) and the JavaScript language to manipulate the properties and methods of XHTML tags in response to user or browser events. Under ASP.NET, these same stylings can take place, in this case through control settings and server scripts rather than CSS and browser scripts.

Dynamic HTML

Browser-based DHTML methods are illustrated by the following button that changes its visual characteristics when clicked. In this case, CSS property settings are applied to the button under local script control.


Figure 2-45. Using DHTML to style an XHTML tag.
<script type="text/javascript">
function ChangeFormat()
{
  document.getElementById("MyButton").style.backgroundColor = "#FF0000"
  document.getElementById("MyButton").style.color = "#FFFFFF"
  document.getElementById("MyButton").style.fontFamily = "comic sans ms"
  document.getElementById("MyButton").value = "Thank You"
}
</script>

<input id="MyButton" type="button" value="Click Me" onclick="ChangeFormat()"
  style="background-color:#F0F0F0; color:#990000"/>
Listing 2-51. Code for DHTML to style an XHTML tag.

The button is styled originally with an in-line CSS style sheet setting the background and text colors. This button also is given an id (MyButton) for reference in the accompanying browser script written in the JavaScript language. The ChangeFormat() function is called on a mouse click to dynamically set various CSS styles for the button to change its appearance. All scripting is local to the browser.

Dynamic Server CSS Styling

The identical style changes can be made to occur with a server script. The requirement is that the button needs to be a server control to make it accessible by the script.


Figure 2-46. Using a server script to set CSS properties for a server control.
<SCRIPT Runat="Server">

Sub Change_Format (Src As Object, Args As EventArgs)

  MyButton.Style("background-color") = "#FF0000"
  MyButton.Style("color") = "#FFFFFF"
  MyButton.Style("font-family") = "comic sans ms"
  MyButton.Text = "Thank You"
	
End Sub

</SCRIPT>

<form Runat="Server">

<asp:Button id="MyButton" Text="Click Me" Runat="Server"
  Style="background-color:#F0F0F0; color:#990000" OnClick="Change_Format"/>
	
</form>
Listing 2-52. Code to use server CSS properties to style a server control.

Again, the button is originally styled with CSS properties coded in the Style attribute of the control in the same way that XHTML tags are styled with in-line CSS style sheets. The subprogram called by the button click dynamically sets CSS styles for the button through this same Style property. Notice also that the button's label is changed by assigning a new value to its Text property.

Notice the format for applying CSS style settings through server scripts. Any CSS style can be applied to any server control using this method.

ControlId.Style("CSS property") = "value"
Figure 2-47. General format to set CSS style properties for a server control

In addition to applying individual CSS styles to a server control, a script can apply style classes by assigning it a CSSClass property. The control then takes on style properties predefined in embedded or linked stylesheets.

ControlId.CSSClass = "class"
Figure 2-48. General format to apply a CSS style class to a server control

The following embedded style sheet defines two style classes: .normalButton is assigned as the initial button display and .clickedButton is assigned dynamically to the button by a subprogram call.


Figure 2-49. Using a server CSSClass property to style a server control.
<SCRIPT Runat="Server">

Sub Change_Format (Src As Object, Args As EventArgs)

  MyButton.CSSClass = "clickedButton"
  MyButton.Text = "Thank You"

End Sub

</SCRIPT>

<head>
<style type="text/css">
  .normalButton  {background-color:#F0F0F0; color:#990000}
  .clickedButton {background-color:#FF0000; color:#FFFFFF; 
                  font-family:comic sans ms}
</style>
</head>

<form Runat="Server">

<asp:Button id="MyButton" Text="Click Me" OnClick="Change_Format"
  class="normalButton" Runat="Server"/>

</form>
Listing 2-53. Code to apply a CSS style class to a server control.

Style class .normalButton is initially assigned with in-line coding in the server control in exactly the same way as any XHTML tag is assigned a style class from an embedded style sheet. In addition, the server script makes reference to this same style sheet, applying the .clickedButton class in response to a subprogram call. Effectively, the style sheet is accessible both in the browser and on the server.

Using a Subprogram's Arguments

In the previous examples, CSS styling is applied to a single button by calling a single subprogram. Using this technique, duplicate subprograms would be needed if there were multiple buttons to be styled in the same fashion. You can, however, make use of a button's subprogram argument list to effect styling of multiple controls through a single subprogram.

Recall that the identify of the control which makes a subprogram call is given in the first argument in the subprogram's argument list—Src As Object in the above subprograms. The reference Src, then, is a reference to the calling control, and can be used to set properties of the control making the call.

The following example shows three buttons, each of which is styled with CSS style properties issued through the same subprogram.


Figure 2-50. Using a single subprogram call to style multiple buttons.

In this case, the button's self-reference (Src) in the subprogram's argument list is used as the identify of which button to style, that is, the button that was clicked and that called the subprogram.

<SCRIPT language="vb" Runat="Server">

Sub Change_Format (Src As Object, Args As EventArgs)

  Src.Style("background-color") = "#FF0000"
  Src.Style("color") = "#FFFFFF"
  Src.Style("font-family") = "comic sans ms"
  Src.Text = "Thank You"
	
End Sub

</SCRIPT>

<form Runat="Server">

<asp:Button id="Button1" Text="Click Me" onClick="Change_Format"
  Style="background-color:#F0F0F0; color:#990000" Runat="Server"/>
<asp:Button id="Button2" Text="Click Me" onClick="Change_Format"
  Style="background-color:#F0F0F0; color:#990000" Runat="Server"/>
<asp:Button id="Button3" Text="Click Me" onClick="Change_Format"
  Style="background-color:#F0F0F0; color:#990000" Runat="Server"/>

</form>
Listing 2-54. Code to set multiple button styles with a single subprogram.

The principle in effect in the above styling examples is that common CSS style settings can take place in the browser, on the server, or in any combination of scripting involving the two. They can be assigned dynamically through browser scripts written in JavaScript and through server scripts written in Visual Basic.

Server Style Properties

A third method of styling server controls is by using a set of special properties recognized only by ASP.NET. The common properties that can be applied to most server controls are described in Figure 2.51 along with their CSS equivalents.

Server Property Description CSS Equivalent
AccessKey Alt-Key keyboard shortcut for selecting control. accesskey
BackColor Background color of control. Value given by color name or hex or rgb value. background-color
BorderColor Color of border style. Value given by color name or hex or rgb value. border-color
BorderStyle Appearance of border around control. Values include Dashed, Dotted, Double,Groove, Inset, None, NotSet, Outset, Ridge, Solid border-style
BorderWidth Thickness of a border, in pixels. border-width
Enabled True or False to dim the inactive control. disabled
Font-Bold Displays bold text. font-weight
Font-Italic Displays italic text. font-style
Font-Name Specifies a single typeface for formatting text. font-family
Font-Names Specifies a comma-separated list of typefaces for formatting text. First available typeface in list is applied. font-family
Font-Overline Draws a line above the text. text-decoration:overline
Font-Size Specifies the text size in points or pixels. font-size
Font-Strikeout Draws a line through the text. border-color
Font-Underline Draws a line beneath the text. text-decoration:underline
ForeColor Specifies the text color. color
Height Specifies the height of the control in pixels. height
HorizontalAlign Left, Center, Right, or Justify to indicate alignment of text within a control. align
HorizontalPadding Specifies the amount of space, in pixels, to leave between the left and right of a control and its contents. Applicable to certain controls. padding-left; padding-right
ScrollBars Auto, Horizontal, Vertical, Both, or None to indicate appearance of scroll bars for a text control. overflow
TabIndex Specifies the order of tabbing of the control. taborder
ToolTip Specifies a text string to display in a pop-up box when the cursor hovers over the control. title
VerticalAlign Top, Middle, or Bottom to indicate alignment of text in a table cell display. vertical-align
VerticalPadding Specifies the amount of space, in pixels, to leave between the top and bottom of a control and its contents. Applicable to certain controls. padding-top; padding-bottom
Visible True or False to indicate whether a control is visible or hidden. display; visibility
Width Specifies the width of the control in pixels. width
Wrap True or False to indicate text wrapping for a cell in a table display. wrap
Figure 2-51. Common properties for server controls.

As you can see, most of the server properties have CSS equivalents. Certain CSS styles, however, do not have server equivalents, or they are not available for all controls. For instance, the CSS padding style, which introduces white space surrounding the contents of an XHTML tag, does not have a matching server style property that works for all controls.

These server properties are applied in two ways. They can be coded as part of the original control definition, or they can be scripted to set or change properties dynamically. An example of applying some of these server properties in code and changing them in script is illustrated by the following button.


Figure 2-52. Applying server style properties to a server control.
<%@ Import Namespace="System.Drawing" %>

<SCRIPT Runat="Server">

Sub Change_Format (Src As Object, Args As EventArgs)

  Src.BackColor = Color.FromName("#FF0000")
  Src.Font.Name = "Comic Sans MS"
  Src.Font.Size = FontUnit.Parse("12pt")
  Src.Width = Unit.Parse("150px")
  Src.Height = Unit.Parse("50px")
  Src.BorderStyle = BorderStyle.Inset
  Src.Text = "Thank You"

End Sub

</SCRIPT>

<form Runat="Server">

<asp:Button Text="Click Me" OnClick="Change_Format" Runat="Server"
  BackColor="SteelBlue"
  ForeColor="#FFFFFF"
  BorderStyle="Outset"
  BorderWidth="5"
  BorderColor="Silver"
  Width="150"
  Height="50"
  Style="padding:10px; cursor:hand"/>

</form>
Listing 2-55. Code to apply server style properties to a server control.

Scripted Server Styles

It can be a little more troublesome setting certain server properties through script rather than setting CSS styles through script. First, in order to set colors, font sizes, measurement units, and other values programmatically, the System.Drawing namespace must be imported to the page.

<%@ Import Namespace="System.Drawing" %>
Listing 2-56. Importing the System.Drawing namespace for scripting server style properties.

Second, notice that certain of the coded properties are hyphenated: Font-Name, Font-Bold, Font-Italic, for example. These hyphenated names are used when coding styles declaratively, that is, when creating the control. When scripting these same styles, the hyphenated names are coded in dotted notation, with the hyphen being replaced by a period: Font.Name, Font.Bold, Font.Italic.

Third, certain of the style values must be scripted in special ways. For instance, color values must be converted from their color name or hexadecimal equivalents with the Color.FromName() method. The same goes for converting font sizes with the FontUnit.Parse() method, for making width and height settings with the Unit.Parse() method, for setting border styles with the BorderStyle.type enumeration, and others. These scripted property names and their scripted value formats are shown in the following table.

Scripted Property Scripted Value
BackColor Color.FromName("colorname"|"hexvalue")
BorderColor Color.FromName("colorname|hexvalue")
BorderStyle BorderStyle.Dashed
BorderStyle.Dotted
BorderStyle.Double
BorderStyle.Groove
BorderStyle.Inset
BorderStyle.None
BorderStyle.NotSet
BorderStyle.Outset
BorderStyle.Ridge
BorderStyle.Solid
BorderWidth Unit.Parse("npx")
Font.Bold True|False
Font.Italic True|False
Font.Name "fontname"
Font.Names "fontname1 [,fontname2]..."
Font.Overline True|False
Font.Size FontUnit.Parse("npt")
Font.Strikeout True|False
Font.Underline True|False
ForeColor Color.FromName("colorname|hexvalue")
Height Unit.Parse("npx")
HorizontalAlign HorizontalAlign.Left
HorizontalAlign.Center
HorizontalAlign.Right
HorizontalAlign.Justify
HorizontalPadding Unit.Parse("npx")
ScrollBars ScrollBars.Auto
ScrollBars.Horizontal
ScrollBars.Vertical
ScrollBars.Both
ScrollBars.None
TextAlign TextAlign.Left
TextAlign.Right
VerticalAlign VerticalAlign.Top
VerticalAlign.Middle
VerticalAlign.Bottom
VerticalPadding Unit.Parse("npx")
Visible True|False
Width Unit.Parse("npx")
Wrap True|False
Figure 2-53. Scripted properties and values.

The previous script uses some of these special conversions to change server style properties of the Button control.

Src.BackColor = Color.FromName("#FF0000")
Src.Font.Name = "Comic Sans MS"
Src.Font.Size = FontUnit.Parse("12pt")
Src.Width = Unit.Parse("150px")
Src.Height = Unit.Parse("50px")
Src.BorderStyle = BorderStyle.Inset
Listing 2-57. Applying scripted properties to a server control.

Scripted CSS Styles

An alternative to these server style conversions is to style the control declaratively with server properties and to style it programmatically with CSS properties to avoid System.Drawing conversions. The following recoding of the above button takes this tactic.

<SCRIPT Runat="Server">

Sub Change_Format (Src As Object, Args As EventArgs)

  Src.Style("background-color") = "#FF0000"
  Src.Style("font-family") = "comic sans ms"
  Src.Style("font-size") = "12pt"
  Src.Style("width") = "150px"
  Src.Style("height") = "50px"
  Src.Style("border-style") = "inset"
  Src.Text = "Thank You"

End Sub

</SCRIPT>

<form Runat="Server">

<asp:Button Text="Click Me" OnClick="Change_Format" Runat="Server"
  BackColor="SteelBlue"
  ForeColor="#FFFFFF"
  BorderStyle="Outset"
  BorderWidth="5"
  BorderColor="Silver"
  Width="150"
  Height="50"
  Style="padding:10px; cursor:hand"/>

</form>
Listing 2-58. Code to apply scripted CSS style properties to a server control.

Although you can code server style properties in a control and change its styling with scripted CSS styles, the reverse is not true. If the control is initially styled with CSS properties, for instance,

<asp:Button Text="Click Me" OnClick="Change_Format" Runat="Server"
  Style="background-color:steelblue; color:#FFFFFF; border-style:outset;
  border-width:5px; border-color:silver; width:150px; height:50px;
  padding:10px; cursor:hand"/>
Listing 2-59. Code to apply declarative CSS style properties to a server control.

scripted server properties will not change these styles! Scripted server styles only change declarative server styles, not declarative CSS styles.

A variety of styling methods are used in these tutorials, with no one method particularly favored. For certain controls, server properties are a more natural means to apply styles; for other controls, the comfort of CSS styling is favored. It is well to be flexible to get the most out of the variety of styling methods available.

Server-based Development

The question can be raised: Why learn a whole new set of server style properties when CSS styles work so well? One reason is that CSS styles are primarily browser-based styles. They are applied with browser style sheets and changed with browser scripts. They are a browser phenomenon. ASP.NET properties, on the other hand, are exclusively server based and are designed to work with server controls. Besides, they respresent only a tiny portion of the many properties, styling and otherwise, associated with server controls. They fit with the whole idea behind server-based control properties.

A second and more substantial reason for using server style properties is a trend away from browser-based processing—away from the use of browser style sheets and browser scripting—in favor of server-based processing. You have seen that even XHTML tags are being replaced by server controls, again, moving browser coding to the server. You will see later how XML files and XSLT style sheets processed through server scripts can create an entire Web page without any XHTML coding at all. This trend from browser-based coding to server-based coding is likely to continue.

This trend does not mean, however, the disappearance of XHTML, CSS style sheets, or browser scripting. After all, these are the only page elements and languages understood by browsers. Rather, the trend means that Web page development is moving to a server-based environment with server-based languages; Web page display remains a browser-based phenomenon, using standard XHTML, CSS style sheets, and the JavaScript language. One of the main tasks of the ASP.NET processor is, in fact, to convert the server code in ASP.NET pages to code understandable by browsers. If you view your browser's source listing for an ASP.NET page, you will see only standard XHTML, CSS style sheets, and JavaScript code. Server code needs to be converted to browser code for proper page display. Be prepared, though, to abandon much of the XHTML, CSS, and JavaScript coding traditional to Web page development and to adopt their server equivalents in designing and coding Web pages.

Neither does this trend mean you can rest in ignorance about browser languages. You still need understanding of XHTML, CSS, and JavaScript in order to interpret the code delivered to the browser. Sometimes it is necessary to inspect this code to figure out what went wrong. As well, there may be certain page design goals that cannot yet be accomplished with only server code. You will need to rely on your knowledge of browser languages to accomplish these outcomes. Thus, browser languages and server languages both are intregal partners in Web page design.