Keyboard shortcuts for Windows

Windows system key combinations

  • F1: Help
  • CTRL+ESC: Open Start menu
  • ALT+TAB: Switch between open programs
  • ALT+F4: Quit program
  • SHIFT+DELETE: Delete item permanently
  • Windows Logo+L: Lock the computer (without using CTRL+ALT+DELETE)

Windows program key combinations

  • CTRL+C: Copy
  • CTRL+X: Cut
  • CTRL+V: Paste
  • CTRL+Z: Undo
  • CTRL+B: Bold
  • CTRL+U: Underline
  • CTRL+I: Italic

Mouse click/keyboard modifier combinations for shell objects

  • SHIFT+right click: Displays a shortcut menu containing alternative commands
  • SHIFT+double click: Runs the alternate default command (the second item on the menu)
  • ALT+double click: Displays properties
  • SHIFT+DELETE: Deletes an item immediately without placing it in the Recycle Bin

General keyboard-only commands

  • F1: Starts Windows Help
  • F10: Activates menu bar options
  • SHIFT+F10 Opens a shortcut menu for the selected item (this is the same as right-clicking an object
  • CTRL+ESC: Opens the Start menu (use the ARROW keys to select an item)
  • CTRL+ESC or ESC: Selects the Start button (press TAB to select the taskbar, or press SHIFT+F10 for a context menu)
  • CTRL+SHIFT+ESC: Opens Windows Task Manager
  • ALT+DOWN ARROW: Opens a drop-down list box
  • ALT+TAB: Switch to another running program (hold down the ALT key and then press the TAB key to view the task-switching window)
  • SHIFT: Press and hold down the SHIFT key while you insert a CD-ROM to bypass the automatic-run feature
  • ALT+SPACE: Displays the main window's System menu (from the System menu, you can restore, move, resize, minimize, maximize, or close the window)
  • ALT+- (ALT+hyphen): Displays the Multiple Document Interface (MDI) child window's System menu (from the MDI child window's System menu, you can restore, move, resize, minimize, maximize, or close the child window)
  • CTRL+TAB: Switch to the next child window of a Multiple Document Interface (MDI) program
  • ALT+underlined letter in menu: Opens the menu
  • ALT+F4: Closes the current window
  • CTRL+F4: Closes the current Multiple Document Interface (MDI) window
  • ALT+F6: Switch between multiple windows in the same program (for example, when the Notepad Find dialog box is displayed, ALT+F6 switches between the Find dialog box and the main Notepad window)

Shell objects and general folder/Windows Explorer shortcuts

For a selected object:
  • F2: Rename object
  • F3: Find all files
  • CTRL+X: Cut
  • CTRL+C: Copy
  • CTRL+V: Paste
  • SHIFT+DELETE: Delete selection immediately, without moving the item to the Recycle Bin
  • ALT+ENTER: Open the properties for the selected object

To copy a file

Press and hold down the CTRL key while you drag the file to another folder.

To create a shortcut

Press and hold down CTRL+SHIFT while you drag a file to the desktop or a folder.

General folder/shortcut control

  • F4: Selects the Go To A Different Folder box and moves down the entries in the box (if the toolbar is active in Windows Explorer)
  • F5: Refreshes the current window.
  • F6: Moves among panes in Windows Explorer
  • CTRL+G: Opens the Go To Folder tool (in Windows 95 Windows Explorer only)
  • CTRL+Z: Undo the last command
  • CTRL+A: Select all the items in the current window
  • BACKSPACE: Switch to the parent folder
  • SHIFT+click+Close button: For folders, close the current folder plus all parent folders

Windows Explorer tree control

  • Numeric Keypad *: Expands everything under the current selection
  • Numeric Keypad +: Expands the current selection
  • Numeric Keypad -: Collapses the current selection.
  • RIGHT ARROW: Expands the current selection if it is not expanded, otherwise goes to the first child
  • LEFT ARROW: Collapses the current selection if it is expanded, otherwise goes to the parent

Properties control

  • CTRL+TAB/CTRL+SHIFT+TAB: Move through the property tabs

Accessibility shortcuts

  • Press SHIFT five times: Toggles StickyKeys on and off
  • Press down and hold the right SHIFT key for eight seconds: Toggles FilterKeys on and off
  • Press down and hold the NUM LOCK key for five seconds: Toggles ToggleKeys on and off
  • Left ALT+left SHIFT+NUM LOCK: Toggles MouseKeys on and off
  • Left ALT+left SHIFT+PRINT SCREEN: Toggles high contrast on and off

Microsoft Natural Keyboard keys

  • Windows Logo: Start menu
  • Windows Logo+R: Run dialog box
  • Windows Logo+M: Minimize all
  • SHIFT+Windows Logo+M: Undo minimize all
  • Windows Logo+F1: Help
  • Windows Logo+E: Windows Explorer
  • Windows Logo+F: Find files or folders
  • Windows Logo+D: Minimizes all open windows and displays the desktop
  • CTRL+Windows Logo+F: Find computer
  • CTRL+Windows Logo+TAB: Moves focus from Start, to the Quick Launch toolbar, to the system tray (use RIGHT ARROW or LEFT ARROW to move focus to items on the Quick Launch toolbar and the system tray)
  • Windows Logo+TAB: Cycle through taskbar buttons
  • Windows Logo+Break: System Properties dialog box
  • Application key: Displays a shortcut menu for the selected item

Microsoft Natural Keyboard with IntelliType software installed

  • Windows Logo+L: Log off Windows
  • Windows Logo+P: Starts Print Manager
  • Windows Logo+C: Opens Control Panel
  • Windows Logo+V: Starts Clipboard
  • Windows Logo+K: Opens Keyboard Properties dialog box
  • Windows Logo+I: Opens Mouse Properties dialog box
  • Windows Logo+A: Starts Accessibility Options (if installed)
  • Windows Logo+SPACEBAR: Displays the list of Microsoft IntelliType shortcut keys
  • Windows Logo+S: Toggles CAPS LOCK on and off

Dialog box keyboard commands

  • TAB: Move to the next control in the dialog box
  • SHIFT+TAB: Move to the previous control in the dialog box
  • SPACEBAR: If the current control is a button, this clicks the button. If the current control is a check box, this toggles the check box. If the current control is an option, this selects the option.
  • ENTER: Equivalent to clicking the selected button (the button with the outline)
  • ESC: Equivalent to clicking the Cancel button
  • ALT+underlined letter in dialog box item: Move to the corresponding item

Creating Your First ASP.NET 4 Web Site

1. Start VWD 2008-2010 from the Windows Start menu if you haven’t done so already. The first time you start VWD, there might be a delay before you can use VWD because it’s busy configuring itself. Subsequent starts of the application will go much faster.
2. If you’re using a commercial version of Visual Studio, you also get a dialog box that lets you choose between different collections of settings the first time you start Visual Studio. The choice you make on that dialog box influences the layout of windows, toolboxes, menus, and shortcuts. Choose the Web Development settings because those settings are designed specifically for ASP.NET developers. You can always choose a different profile later by resetting your settings, as explained later in this chapter.
3. Once VWD is fully configured, you see the main screen appear, as shown in Figure 1-2.
Visual Web Developer 2010 main screen
Figure 1-2
You get a full description of all the windows, toolbars, panels, and menus in the next section, so for now, just focus on creating a new web site. Click the File menu in the upper-left corner and choose New Web Site. If you’re using a commercial version of Visual Studio, depending on the settings you chose when starting Visual Studio the first time, you may have to open the submenu New first. (Make sure you don’t accidentally use the New Project menu, because that is used to create different types of .NET applications.) The New Web Site dialog box appears as shown in Figure 1-3.
Visual Web Developer 2010 New Web Site dialog box
Figure 1-3
4. In the Installed Templates section on the left you can choose a programming language you will use for your site. This book shows all examples in both Visual Basic and Visual C# so you can choose a language to your liking.
5. In the list with templates in the middle, verify that ASP.NET Web Site is selected. Verify that File System is the selected option in the Web Location drop-down list at the bottom left. If you want, you could change the location on disk where the web site is stored by clicking the Browse button and choosing a new location on your computer’s hard drive. For now, the default location — a folder under your Documents folder — is fine, so you can leave the location as is.
6. Click OK. VWD creates a new web site for you that includes a number of files and folders to jump start your web site as shown in Figure 1-4. It also opens the file Default.aspx so you can see the code for the page.
Files and folders Visual Web Developer 2010 creates to jump start your web site
Figure 1-4
7. Remove the code inside the <asp:Content> block (it starts with <h2> and ends with </p>) and replace it with the following bolded text and code:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
  <h2>Hello World</h2>
  <p>Welcome to Beginning ASP.NET 4 on <%= DateTime.Now.ToString() %></p>
</asp:Content>
You’ll see code formatted like this a lot more in this book. When you are instructed to type in code formatted like this with some code in bold, you only need to type in the highlighted code. The other code should already be present in the file.
Don’t worry about the code with the angle brackets (<>) and percentage symbol in the welcome message; you learn how it works later. Although this code may not look familiar to you now, you can probably guess what it does: it writes out today’s date and time.
8. Press Ctrl+F5 to open the page in your default web browser. You see a page similar to the one shown in Figure 1-5.
Default ASP.NET 4 web page in Visual Web Developer 2010 opened in your default browser
Figure 1-5
If you get a dialog box asking for your user name and password, close your browser and go back to VWD. Right-click your site in the Solution Explorer (it’s the first item in Figure 1-4) and choose Property Pages. In the Start Options section clear the checkbox for the NTLM Authentication item. Then click OK and press Ctrl+F5 again to view the page in the browser. If you see an information bar warning about Intranet settings in Internet Explorer, click the bar and choose Enable Intranet Settings. If you want to learn more about the implications of these settings first, choose What are Intranet Settings from the popup menu.
If you don’t see the date and time in the page, or if you get an error, look again at the code in the welcome message. It starts with an angle bracket (<) followed by a percentage symbol and an equals sign. It closes with a single percentage sign and another angle bracket (>). Also, make sure you typed in the code exactly as shown here, including capitalization. This is especially true when you are using C#, because that language is case sensitive.
9. Notice how a small icon with a screen tip appeared in the tray bar of Windows, visible in Figure 1-6.
If you don’t see the icon, right-click the arrow near the other icons in the Windows tray and choose Customize Notification Icons. Then set the WebDev.WebServer40.exe option to Show Icon and Notifications. The icon belongs to the ASP.NET Development Server. This web server has been started by VWD automatically to serve the request for your page. You learn more about how the web server processes your page later in this chapter.
Visual Web Developer ASP.NET Development Server icon in the Windows tray bar
Figure 1-6
That’s it. You just created your very first ASP.NET 4 web site with VWD.
How It Works
Although the web site you created in this Try It Out is quite simple, the process that eventually results in the page Default.aspx being displayed in your browser isn’t so simple. All by itself, an ASP.NET page (also referred to as an ASPX page because of its extension) can’t do much. It needs to be processed and served by a web server before your browser can display it. That’s why VWD automatically started up the built-in ASP.NET Development Server to handle the request for the page. Next, it started up your default web browser and directed it to the address of the web server, http://localhost:49212/WebSite1/Default.aspx in the Try It Out example, although the actual number in the address may change every time you start the web server because the number is randomly chosen by VWD.
It’s important to realize that the ASPX file you modified in VWD is not the same as the one that eventually gets displayed by the browser.
When you create a page in VWD, you add markup to it. The markup in an ASPX page is a combination of plain text, HTML, code for ASP.NET Server Controls (which you learn more about in this chapter and in Chapter 4), code written in Visual Basic.NET or C#, and more.
When you request an ASPX page in your browser, the web server processes the page, executes any code it finds in the file, and effectively transforms the ASP.NET markup into plain HTML that it then sends to the browser, where it is displayed. In the preceding Try It Out, the resulting HTML causes the browser to display the current date and time. HTML, or HyperText Markup Language, is the language that browsers use to display a web page. You learn how HTML looks and how to use it later in this chapter.
To see how the final HTML differs from the original ASPX page, open the source for the page in your browser. In most browsers, you can bring up the source window by right-clicking the page in the browser and choosing View Source or View Page Source. This brings up your default text editor, showing the HTML for the page.
If you already closed your browser after the preceding Try It Out, press Ctrl+F5 in VWD to open the page and choose View Source again.
Most of the HTML you see in the text editor is similar to the original ASPX page. However, if you look at the line that displays the welcome message and the current date and time, you’ll notice a big difference. Instead of the code between the angle brackets and percentage signs, you now see the actual date and time:
<div class="main">
  <h2>Hello World</h2>
  <p>Welcome to Beginning ASP.NET 4 on 10/30/2009 6:19:16 PM</p>
</div>
When the web server processed the page, it looked up the current date and time from the server, and inserted it in the HTML that got sent to the browser. Depending on the language settings of your Windows installation, you may see the date and time formatted differently to accommodate the Windows Regional Settings.

Creating a Simple Web-Based Calculator with ASP.NET 4

In this exercise you create a simple calculator that is able to add, subtract, multiply, and divide values. It shows you how to use some of the logical and assignment operators and demonstrates the If and Select Case / switch constructs.
1. Start by creating a new Web Form called CalculatorDemo.aspx in the Demos folder. Make sure you don’t name the page Calculator or you’ll run into troubles later in this chapter where you create a class by that name. Once again, make sure you’re using the Code Behind model and select the correct programming language.
2. Switch the page to Design View, and click in the dashed rectangle to put the focus on it. Choose Table Ø Insert Table from the main menu and add a table with three rows and three columns. Merge all three cells of the first row by selecting them, right-clicking the selection, and choosing Modify Ø Merge Cells from the menu that appears.
3. Add the following controls to the page, set their ID and other properties as in the following table, and arrange the controls as shown in Figure 5-3. 
Control Type
Control ID
Property Settings
Label
ResultLabel
Clear its Text property. To do this, right-click the property name in the Properties Grid and choose Reset.
TextBox
ValueBox1
 
DropDownList
OperatorList
Add four ListItems for the following arithmetic operators using the DropDownList’s Smart Tasks panel.
+
-
*
/
TextBox
ValueBox2
 
Button
CalculateButton
Set the Text property of the button to Calculate.
When you’re done, your page should look like Figure 5-3 in Design View.
ASP.NET calculator example
Figure 5-3
4. Double-click the Calculate button and add the following bolded code in the code placeholder that VWD added for you:
VB.NET
Protected Sub CalculateButton_Click(ByVal sender As Object,
         ByVal e As System.EventArgs) Handles CalculateButton.Click
  If ValueBox1.Text.Length > 0 AndAlso ValueBox2.Text.Length > 0 Then

    Dim result As Double = 0
    Dim value1 As Double = Convert.ToDouble(ValueBox1.Text)
    Dim value2 As Double = Convert.ToDouble(ValueBox2.Text)

    Select Case OperatorList.SelectedValue
      Case "+"
        result = value1 + value2
      Case "-"
        result = value1 - value2
      Case "*"
        result = value1 * value2
      Case "/"
        result = value1 / value2
    End Select
    ResultLabel.Text = result.ToString()
  Else
    ResultLabel.Text = String.Empty
  End If
End Sub
C#
protected void CalculateButton_Click(object sender, EventArgs e)
{
  if (ValueBox1.Text.Length > 0 && ValueBox2.Text.Length > 0)
  {
    double result = 0;
    double value1 = Convert.ToDouble(ValueBox1.Text);
    double value2 = Convert.ToDouble(ValueBox2.Text);

    switch (OperatorList.SelectedValue)
    {
      case "+":
        result = value1 + value2;
        break;
      case "-":
        result = value1 - value2;
        break;
      case "*":
        result = value1 * value2;
        break;
      case "/":
        result = value1 / value2;
        break;
    }
    ResultLabel.Text = result.ToString();
  }
  else
  {
    ResultLabel.Text = string.Empty;
  }
}
5. Save all changes and press Ctrl+F5 to open the page in the browser. If you get an error instead of seeing the page, make sure you typed the code exactly as shown here, and that you named all controls according to the table you saw earlier.
6. Enter a number in the first and second text boxes, choose an operator from the drop-down list, and click the Calculate button. The code in the Code Behind fires and then — based on the item you selected in the drop-down list — the correct calculation is performed and the label is updated with the result.
7. Go ahead and try some other numbers and operators; you’ll see that the calculator carries out the right operation every time you click the Calculate button.
How It Works
When you enter two values and click the Calculate button, the following code in the Code Behind fires:
VB.NET
If ValueBox1.Text.Length > 0 AndAlso ValueBox2.Text.Length > 0 Then
C#
if (ValueBox1.Text.Length > 0 && ValueBox2.Text.Length > 0)
This code is necessary to ensure that both text boxes contain a value. (In Chapter 9 you see a much cleaner way to perform this validation.) The code uses a simple If statement to ensure that both fields have a value. It also uses AndAlso or && to avoid checking the Text property of the second TextBox when the first is empty.
The code then declares a Double to hold the result of the calculation and then gets the values from the two text box controls, converts the values to a Double using the ToDouble method of the Convert class, and then sets up a Select Case (switch in C#) block to handle the type of operator you have chosen in the drop-down list:
VB.NET
Select Case OperatorList.SelectedValue
  Case "+"
  result = value1 + value2
C#
switch (OperatorList.SelectedValue)
{
  case "+":
    result = value1 + value2;
    break;
For each item in the drop-down list, there is a case statement. When you have chosen the + operator from the list, the code in the first case block will fire, and result is assigned the sum of the numbers you entered in the two text boxes. Likewise, when you choose the subtraction operator, for example, the two values are subtracted from each other.
At the end, the result is converted to a String and then displayed on the label called ResultLabel.
The Select Case / switch statements close off the discussion about making decisions in your code. There’s one more group of statements left: Loops that enable you to loop over code or over objects in a collection.

Creating a Site-Wide Layout Using Master Pages (C#)

Introduction

One attribute of a well-designed website is a consistent site-wide page layout. Take the www.asp.net website, for example. At the time of this writing, every page has the same content at the top and bottom of the page. As Figure 1 shows, the very top of each page displays a gray bar with a list of Microsoft Communities. Beneath that is the site logo, the list of languages into which the site has been translated, and the core sections: Home, Get Started, Learn, Downloads, and so forth. Likewise, the bottom of the page includes information about advertising on www.asp.net, a copyright statement, and a link to the privacy statement.
Figure 01: The www.asp.net Website Employs a Consistent Look and Feel Across All Pages (Click to view full-size image)
Another attribute of a well-designed site is the ease with which the site's appearance can be changed. Figure 1 shows the www.asp.net homepage as of March 2008, but between now and this tutorial's publication, the look and feel may have changed. Perhaps the menu items along the top will expand to include a new section for the MVC framework. Or maybe a radically new design with different colors, fonts, and layout will be unveiled. Applying such changes to the entire site should be a fast and simple process that does not require modifying the thousands of web pages that make up the site.
Creating a site-wide page template in ASP.NET is possible through the use of master pages. In a nutshell, a master page is a special type of ASP.NET page that defines the markup that is common among all content pages as well as regions that are customizable on a content page-by-content page basis. (A content page is an ASP.NET page that is bound to the master page.) Whenever a master page's layout or formatting is changed, all of its content pages' output is likewise immediately updated, which makes applying site-wide appearance changes as easy as updating and deploying a single file (namely, the master page).
This is the first tutorial in a series of tutorials that explore using master pages. Over the course of this tutorial series we:
  • Examine creating master pages and their associated content pages,
  • Discuss a variety of tips, tricks, and traps,
  • Identify common master page pitfalls and explore workarounds,
  • See how to access the master page from a content page and vice-a-versa,
  • Learn how to specify a content page's master page at runtime, and
  • Other advanced master page topics.
These tutorials are geared to be concise and provide step-by-step instructions with plenty of screen shots to walk you through the process visually. Each tutorial is available in C# and Visual Basic versions and includes a download of the complete code used.
This inaugural tutorial starts with a look at master page basics. We discuss how master pages work, look at creating a master page and associated content pages using Visual Web Developer, and see how changes to a master page are immediately reflected in its content pages. Let's get started!

Understanding How Master Pages Work

Building a website with a consistent site-wide page layout requires that each web page emit common formatting markup in addition to its custom content. For example, while each tutorial or forum post on www.asp.net have their own unique content, each of these pages also render a series of common <div> elements that display the top-level section links: Home, Get Started, Learn, and so on.
There are a variety of techniques for creating web pages with a consistent look and feel. A naive approach is to simply copy and paste the common layout markup into all web pages, but this approach has a number of downsides. For starters, every time a new page is created, you must remember to copy and paste the shared content into the page. Such copying and pasting operations are ripe for error as you may accidentally copy only a subset of the shared markup into a new page. And to top it off, this approach makes replacing the existing site-wide appearance with a new one a real pain because every single page in the site must be edited in order to use the new look and feel.
Prior to ASP.NET version 2.0, page developers often placed common markup in User Controls and then added these User Controls to each and every page. This approach required that the page developer remember to manually add the User Controls to every new page, but allowed for easier site-wide modifications because when updating the common markup only the User Controls needed to be modified. Unfortunately, Visual Studio .NET 2002 and 2003 - the versions of Visual Studio used to create ASP.NET 1.x applications - rendered User Controls in the Design view as gray boxes. Consequently, page developers using this approach did not enjoy a WYSIWYG design-time environment.
The shortcomings of using User Controls were addressed in ASP.NET version 2.0 and Visual Studio 2005 with the introduction of master pages. A master page is a special type of ASP.NET page that defines both the site-wide markup and the regions where associated content pages define their custom markup. As we will see in Step 1, these regions are defined by ContentPlaceHolder controls. The ContentPlaceHolder control simply denotes a position in the master page's control hierarchy where custom content can be injected by a content page.
Note: The core concepts and functionality of master pages has not changed since ASP.NET version 2.0. However, Visual Studio 2008 offers design-time support for nested master pages, a feature that was lacking in Visual Studio 2005. We will look at using nested master pages in a future tutorial.
Figure 2 shows what the master page for www.asp.net might look like. Note that the master page defines the common site-wide layout - the markup at the top, bottom, and right of every page - as well as a ContentPlaceHolder in the middle-left, where the unique content for each individual web page is located.
A Master Page Defines the Site-Wide Layout and the Regions Editable on a Content Page-by-Content Page Basis
Figure 02: A Master Page Defines the Site-Wide Layout and the Regions Editable on a Content Page-by-Content Page Basis
Once a master page has been defined it can be bound to new ASP.NET pages through the tick of a checkbox. These ASP.NET pages - called content pages - include a Content control for each of the master page's ContentPlaceHolder controls. When the content page is visited through a browser the ASP.NET engine creates the master page's control hierarchy and injects the content page's control hierarchy into the appropriate places. This combined control hierarchy is rendered and the resulting HTML is returned to the end user's browser. Consequently, the content page emits both the common markup defined in its master page outside of the ContentPlaceHolder controls and the page-specific markup defined within its own Content controls. Figure 3 illustrates this concept.
Figure 03: The Requested Page's Markup is Fused into the Master Page (Click to view full-size image)
Now that we have discussed how master pages work, let's take a look at creating a master page and associated content pages using Visual Web Developer.
Note: In order to reach the widest possible audience, the ASP.NET website we build throughout this tutorial series will be created using ASP.NET 3.5 with Microsoft's free version of Visual Studio 2008, Visual Web Developer 2008. If you have not yet upgraded to ASP.NET 3.5, don't worry - the concepts discussed in these tutorials work equally well with ASP.NET 2.0 and Visual Studio 2005. However, some demo applications may use features new to the .NET Framework version 3.5; when 3.5-specific features are used, I include a note that discusses how to implement similar functionality in version 2.0. Do keep in mind that the demo applications available for download from each tutorial target the .NET Framework version 3.5, which results in a Web.config file that includes 3.5-specific configuration elements and references to 3.5-specific namespaces in the using statements in ASP.NET pages' code-behind classes. Long story short, if you have yet to install .NET 3.5 on your computer then the downloadable web application will not work without first removing the 3.5-specific markup from Web.config. See Dissecting ASP.NET Version 3.5's Web.config File for more information on this topic. You will also need to remove the using statements that reference 3.5-specific namespaces.

Step 1: Creating a Master Page

Before we can explore creating and using master and content pages, we first need an ASP.NET website. Start by creating a new file system-based ASP.NET website. To accomplish this, launch Visual Web Developer and then go to the File menu and choose New Web Site, displaying the New Web Site dialog box (see Figure 4). Choose the ASP.NET Web Site template, set the Location drop-down list to File System, choose a folder to place the web site, and set the language to C#. This will create a new web site with a Default.aspx ASP.NET page, an App_Data folder, and a Web.config file.
Note: Visual Studio supports two modes of project management: Web Site Projects and Web Application Projects. Web Site Projects lack a project file, whereas Web Application Projects mimic the project architecture in Visual Studio .NET 2002/2003 - they include a project file and compile the project's source code into a single assembly, which is placed in the /bin folder. Visual Studio 2005 initially only supported Web Site Projects, although the Web Application Project model was reintroduced with Service Pack 1; Visual Studio 2008 offers both project models. The Visual Web Developer 2005 and 2008 editions, however, only support Web Site Projects. I use the Web Site Project model for my demos in this tutorial series. If you are using a non-Express edition and want to use the Web Application Project model instead, feel free to do so but be aware that there may be some discrepancies between what you see on your screen and the steps you must take versus the screen shots shown and instructions provided in these tutorials.
Figure 04: Create a New File System-Based Web Site (Click to view full-size image)
Next, add a master page to the site in the root directory by right-clicking on the Project name, choosing Add New Item, and selecting the Master Page template. Note that master pages end with the extension .master. Name this new master page Site.master and click Add.
Figure 05: Add a Master Page Named Site.master to the Website (Click to view full-size image)
Adding a new master page file through Visual Web Developer creates a master page with the following declarative markup:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="Site" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 
<title>Untitled Page</title>
 
<asp:ContentPlaceHolder id="head" runat="server">
 
</asp:ContentPlaceHolder>
</head>
<body>
 
<form id="form1" runat="server">
 
<div>
 
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

 
</asp:ContentPlaceHolder>
 
</div>
 
</form>
</body>
</html>

The first line in the declarative markup is the @Master directive. The @Master directive is similar to the @Page directive that appears in ASP.NET pages. It defines the server-side language (C#) and information about the location and inheritance of the master page's code-behind class.
The DOCTYPE and the page's declarative markup appears beneath the @Master directive. The page includes static HTML along with four server-side controls:
  • A Web Form (the <form runat="server">) - because all ASP.NET pages typically have a Web Form - and because the master page may include Web controls that must appear within a Web Form - be sure to add the Web Form to your master page (rather than adding a Web Form to each content page).
  • A ContentPlaceHolder control named ContentPlaceHolder1 - this ContentPlaceHolder control appears within the Web Form and serves as the region for the content page's user interface.
  • A server-side <head> element - the <head> element has the runat="server" attribute, making it accessible through server-side code. The <head> element is implemented this way so that the page's title and other <head>-related markup may be added or adjusted programmatically. For example, setting an ASP.NET page's Title property changes the <title> element rendered by the <head> server control.
  • A ContentPlaceHolder control named head - this ContentPlaceHolder control appears within the <head> server control and can be used to declaratively add content to the <head> element.
This default master page declarative markup serves as a starting point for designing your own master pages. Feel free to edit the HTML or to add additional Web controls or ContentPlaceHolders to the master page.
Note: When designing a master page make sure that the master page contains a Web Form and that at least one ContentPlaceHolder control appears within this Web Form.

Creating a Simple Site Layout

Let's expand Site.master's default declarative markup to create a site layout where all pages share: a common header; a left column with navigation, news and other site-wide content; and a footer that displays the "Powered by Microsoft ASP.NET" icon. Figure 6 shows the end result of the master page when one of its content pages is viewed through a browser. The red circled region in Figure 6 is specific to the page being visited (Default.aspx); the other content is defined in the master page and therefore consistent across all content pages.
Figure 06: The Master Page Defines the Markup for the Top, Left, and Bottom Portions (Click to view full-size image)
To achieve the site layout shown in Figure 6, start by updating the Site.master master page so that it contains the following declarative markup:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="Site" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 
<title>Untitled Page</title>
 
<asp:ContentPlaceHolder id="head" runat="server">
 
</asp:ContentPlaceHolder>
 
<link href="Styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
 
<form id="form1" runat="server">
 
<div id="topContent">
 
<a href="Default.aspx">Master Pages Tutorials</a>
 
</div>

 
<div id="mainContent">
 
<asp:ContentPlaceHolder id="MainContent" runat="server">
 
</asp:ContentPlaceHolder>
 
</div>

 
<div id="leftContent">
 
<h3>Lessons</h3>  
 
<ul>
 
<li>TODO</li>
 
</ul>
 
<h3>News</h3>  
 
<ul>
 
<li>TODO</li>
 
</ul>
 
</div>

 
<div id="footerContent">
 
<img src="Images/PoweredByASPNET.gif" alt="Powered by ASP.NET!" />
 
</div>
 
</form>
</body>
</html>

The master page's layout is defined using a series of <div> HTML elements. The topContent <div> contains the markup that appears at the top of each page, while the mainContent, leftContent, and footerContent <div>s are used to display the page's content, the left column, and the "Powered by Microsoft ASP.NET" icon, respectively. In addition to adding these <div> elements, I also renamed the ID property of the primary ContentPlaceHolder control from ContentPlaceHolder1 to MainContent.
The formatting and layout rules for these assorted <div> elements is spelled out in the Cascading Stylesheet (CSS) file Styles.css, which is specified via a <link> element in the master page's <head> element. These various rules define the look and feel of each <div> element noted above. For example, the topContent <div> element, which displays the "Master Pages Tutorials" text and link, has its formatting rules specified in Styles.css as follows:
#topContent {
 text
-align: right;
 background
-color: #600;
 color
: White;
 font
-size: x-large;
 text
-decoration: none;
 font
-weight: bold;
 padding
: 10px;
 height
: 50px;
}      

If you are following along at your computer, you will need to download this tutorial's accompanying code and add the Styles.css file to your project. Similarly, you will also need to create a folder named Images and copy the "Powered by Microsoft ASP.NET" icon from the downloaded demo website to your project.
Note: A discussion of CSS and web page formatting is beyond the scope of this article. For more on CSS, check out the CSS Tutorials at W3Schools.com. I also encourage you to download this tutorial's accompanying code and play with the CSS settings in Styles.css to see the effects of different formatting rules.

Creating a Master Page Using an Existing Design Template

Over the years I've built a number of ASP.NET web applications for small- to medium-sized companies. Some of my clients had an existing site layout they wanted to use; others hired a competent graphics designer. A few entrusted me to design the website layout. As you can tell by Figure 6, tasking a programmer to design a website's layout is usually as wise as having your accountant perform open-heart surgery while your doctor does your taxes.
Fortunately, there are innumerous websites that offer free HTML design templates - Google returned more than six million results for the search term "free website templates." One of my favorite ones is OpenDesigns.org. Once you find a website template you like, add the CSS files and images to your website project and integrate the template's HTML into your master page.
Note: Microsoft also offers a number of free ASP.NET Design Start Kit Templates that integrate into the New Web Site dialog box in Visual Studio.

Step 2: Creating Associated Content Pages

With the master page created, we are ready to start creating ASP.NET pages that are bound to the master page. Such pages are referred to as content pages.
Let's add a new ASP.NET page to the project and bind it to the Site.master master page. Right-click on the project name in Solution Explorer and choose the Add New Item option. Select the Web Form template, enter the name About.aspx, and then check the "Select master page" checkbox as shown in Figure 7. Doing so will display the Select a Master Page dialog box (see Figure 8) from where you can choose the master page to use.
Note: If you created your ASP.NET website using the Web Application Project model instead of the Web Site Project model you will not see the "Select master page" checkbox in the Add New Item dialog box shown in Figure 7. To create a content page when using the Web Application Project model you must choose the Web Content Form template instead of the Web Form template. After selecting the Web Content Form template and clicking Add, the same Select a Master Page dialog box shown in Figure 8 will appear.
Figure 07: Add a New Content Page (Click to view full-size image)
Figure 08: Select the Site.master Master Page (Click to view full-size image)
As the following declarative markup shows, a new content page contains a @Page directive that points back to its master page and a Content control for each of the master page's ContentPlaceHolder controls.
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="About.aspx.cs" Inherits="About" Title="Untitled Page" %><asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
</asp:Content>

Note: In the "Creating a Simple Site Layout" section in Step 1 I renamed ContentPlaceHolder1 to MainContent. If you did not rename this ContentPlaceHolder control's ID in the same way, your content page's declarative markup will differ slightly from the markup shown above. Namely, the second Content control's ContentPlaceHolderID will reflect the ID of the corresponding ContentPlaceHolder control in your master page.
When rendering a content page, the ASP.NET engine must fuse the page's Content controls with its master page's ContentPlaceHolder controls. The ASP.NET engine determines the content page's master page from the @Page directive's MasterPageFile attribute. As the above markup shows, this content page is bound to ~/Site.master.
Because the master page has two ContentPlaceHolder controls - head and MainContent - Visual Web Developer generated two Content controls. Each Content control references a particular ContentPlaceHolder via its ContentPlaceHolderID property.
Where master pages shine over previous site-wide template techniques is with their design-time support. Figure 9 shows the About.aspx content page when viewed through Visual Web Developer's Design view. Note that while the master page content is visible, it is grayed out and cannot be modified. The Content controls corresponding to the master page's ContentPlaceHolders are, however, editable. And just like with any other ASP.NET page, you can create the content page's interface by adding Web controls through the Source or Design views.
Figure 09: The Content Page's Design View Displays Both the Page-Specific and Master Page Contents (Click to view full-size image)

Adding Markup and Web Controls to the Content Page

Take a moment to create some content for the About.aspx page. As you can see in Figure 10, I entered an "About the Author" heading and a couple of paragraphs of text, but feel free to add Web controls, too. After creating this interface, visit the About.aspx page through a browser.
Figure 10: Visit the About.aspx Page Through a Browser (Click to view full-size image)
It is important to understand that the requested content page and its associated master page are fused and rendered as a whole entirely on the web server. The end user's browser is then sent the resulting, fused HTML. To verify this, view the HTML received by the browser by going to the View menu and choosing Source. Note that there are no frames or any other specialized techniques for displaying two different web pages in a single window.

Binding a Master Page to an Existing ASP.NET Page

As we saw in this step, adding a new content page to an ASP.NET web application is as easy as checking the "Select master page" checkbox and picking the master page. Unfortunately, converting an existing ASP.NET page to a master page is not as easy.
To bind a master page to an existing ASP.NET page you need to perform the following steps:
  1. Add the MasterPageFile attribute to the ASP.NET page's @Page directive, pointing it to the appropriate master page.
  2. Add Content controls for each of the ContentPlaceHolders in the master page.
  3. Selectively cut and paste the ASP.NET page's existing content into the appropriate Content controls. I say "selectively" here because the ASP.NET page likely contains markup that's already expressed by the master page, such as the DOCTYPE, the <html> element, and the Web Form.
For step-by-step instructions on this process along with screen shots, check out Scott Guthrie's Using Master Pages and Site Navigation tutorial. The "Update Default.aspx and DataSample.aspx to use the Master Page" section details these steps.
Because it is much easier to create new content pages than it is to convert existing ASP.NET pages into content pages, I recommend that whenever you create a new ASP.NET website add a master page to the site. Bind all new ASP.NET pages to this master page. Don't worry if the initial master page is very simple or plain; you can update the master page later.
Note: When creating a new ASP.NET application, Visual Web Developer adds a Default.aspx page that isn't bound to a master page. If you want to practice converting an existing ASP.NET page into a content page, go ahead and do so with Default.aspx. Alternatively, you can delete Default.aspx and then re-add it, but this time checking the "Select master page" checkbox.

Step 3: Updating the Master Page's Markup

One of the primary benefits of master pages is that a single master page may be used to define the overall layout for numerous pages on the site. Therefore, updating the site's look and feel requires updating a single file - the master page.
To illustrate this behavior, let's update our master page to include the current date in at the top of the left column. Add a Label named DateDisplay to the leftContent <div>.
<div id="leftContent">
 
<p>
 
<asp:Label ID="DateDisplay" runat="server"></asp:Label>
 
</p>

 
<h3>Lessons</h3>  
 
<ul>
 
<li>TODO</li>
 
</ul>
 
<h3>News</h3>  
 
<ul>
 
<li>TODO</li>
 
</ul>
</div>

Next, create a Page_Load event handler for the master page and add the following code:
protected void Page_Load(object sender, EventArgs e)
{
 
DateDisplay.Text = DateTime.Now.ToString("dddd, MMMM dd");
}

The above code sets the Label's Text property to the current date and time formatted as the day of the week, the name of the month, and the two-digit day (see Figure 11). With this change, revisit one of your content pages. As Figure 11 shows, the resulting markup is immediately updated to include the change to the master page.
Figure 11: The Changes to the Master Page are Reflected When Viewing the a Content Page (Click to view full-size image)

Introduction