You are on page 1of 5286

Visual Studio 2005 Visual Web Developer

Copyright© 2016 Microsoft Corporation

The content in this document is retired and is no longer updated or supported. Some links might not work. Retired content represents the
latest updated version of this content.
Visual Web Developer

Visual Web Developer


Visual Web Developer is a tool for creating and working with ASP.NET Web applications (called simply "Web sites") in a variety
of configurations.
In This Section
Welcome
Provides general information on Visual Web Developer and on improvements and enhancements in the Web development
tool since Visual Studio .NET 2003.
Guided Tour of Creating Web Sites in Visual Web Developer
Lists walkthrough topics (tutorials) that illustrate how to use Visual Web Developer to create and customize Web sites.
ASP.NET Web Sites (Visual Studio)
Provides information on how to create ASP.NET Web applications (sometimes referred to as a Web sites).
ASP.NET Web Pages (Visual Studio)
Provides information about how ASP.NET Web pages function and how to create and program them.
ASP.NET Web Server Controls (Visual Studio)
Provides information about how ASP.NET Web server controls work, how to add them to ASP.NET pages, and how to
program them.
ASP.NET Data Access (Visual Studio)
Provides information on displaying and editing data in ASP.NET Web pages.
ASP.NET Web Site Security (Visual Studio)
Provides information on security threats to your ASP.NET applications, ways to mitigate threats, and ways to authenticate
and authorize users.
ASP.NET Debugging and Troubleshooting (Visual Studio)
Provides information on handling errors, debugging ASP.NET pages, viewing trace information during page processing, and
monitoring the health of your application.
Customizing ASP.NET Web Sites (Visual Studio)
Provides information on enabling your Web site to track individual users, adding navigation features to your site, creating
Web pages for multiple languages and cultures, and creating Web pages that are accessible to people with disabilities.
Managing ASP.NET Web Sites in Visual Studio
Provides information on configuring an ASP.NET Web site, deploying (publishing) Web sites, and managing performance for
your applications.
XML Web Services (Visual Studio)
Provides information on creating and using components that can be accessed across the Web using standard protocols such
as HTTP.
Converting from Visual Studio .NET 2002 or 2003
Provides information on converting Web projects created in Visual Studio .NET 2002 or 2003 to the format used for projects
in Visual Web Developer, including details about how project settings are handled.
ASP.NET Web Sites for Mobile Devices (Visual Studio)
Provides information on features in ASP.NET that help you create applications that can render to browsers in mobile phones
and other devices.
Visual Web Developer

Welcome
This section welcomes you to Visual Studio and provides an overview of the product.
In This Section
What's New in Web Development for Visual Studio
Describes changes and improvements that have been introduced in ASP.NET 2.0.
Visual Web Developer

Introduction to Visual Web Developer


Welcome to Visual Web Developer. Visual Web Developer is a full-featured development environment for creating ASP.NET
Web applications (which are simply called "Web sites"). Visual Web Developer offers you the following features:
Web page design A powerful Web page editor that includes WYSIWYG editing and an HTML editing mode with
IntelliSense and validation.
Page design features Consistent site layout with master pages and consistent page appearance with themes and
skins.
Code editing A code editor that enables you to write code for your dynamic Web pages in Visual Basic or C#. The code
editor includes syntax coloration and IntelliSense.
Debugging A debugger that helps you find errors in your programs.
Controls An extensive suite of ASP.NET Web server controls that incorporate much of the functionality you need for
creating Web sites.
Data access Support for displaying and editing data in your Web pages. The data can be in a variety of data stores,
including databases or XML files. In many cases, you can add data display and editing to your Web pages without writing
any code.
Security, personalization, and more Built-in application services that enable you to add membership for login
security to your site, profile properties that enable you to maintain user-specific information, and other features, most
without requiring any code.
Development for hosted sites Tools for publishing sites to your hosting site, including a local Web server for testing.
Local Development for Hosted Sites
Visual Web Developer provides an ideal environment in which to build Web sites and then publish them to a hosting site.
Using the development tools in Visual Web Developer, you can develop ASP.NET Web pages on your own computer. Visual
Web Developer includes a local Web server that provides all the features you need to test and debug ASP.NET Web pages,
without requiring Internet Information Services (IIS) to be installed.
When your site is ready, you can publish it to the host computer using the built-in Copy Web tool, which transfers your files
when you are ready to share them with others. Alternatively, you can precompile and deploy a Web site by using the Build
Web Site command. The Build Web Site command runs the compiler over the entire Web site (not just the code files) and
produces a Web site layout that you can deploy to a production server.
Note
The Build Web Site feature is not available in Visual Web Developer Express Edition.

Finally, you can take advantage of the built-in support for File Transfer Protocol (FTP). Using the FTP capabilities of Visual Web
Developer, you can connect directly to the host computer and then create and edit files on the server.
Exploring Visual Web Developer
To learn more about creating dynamic Web sites with Visual Web Developer, see the following resources:
The guided tour, which introduces many of the features you will use frequently when creating ASP.NET Web sites. To
start, see Guided Tour of Creating Web Sites in Visual Web Developer.
The ASP.NET 2.0 Starter Kits for Visual Web Developer are complete Web sites that you can use with minor
customization for your own site. These starter kits show you creative ways to use the features of Visual Web Developer to
create professional, functional Web sites. To use a starter kit, create a new Web site and select the starter kit that you
want. Visual Web Developer comes packaged with the Personal Web Site Starter Kit, which creates a Web site that
includes your latest news, a photo album, and other features. For more information, see
Visual Web Developer Starter Kits.
If you need assistance while working with Visual Web Developer, you can refer to the online Help. The Help system can be
extended to take advantage of online information resources as well.
See Also
Other Resources
Guided Tour of Creating Web Sites in Visual Web Developer
Visual Web Developer

What's New in Web Development for Visual Studio


Microsoft Visual Studio 2005 includes the Visual Web Developer Web development tool, which is a set of tools and utilities for
creating ASP.NET version 2.0 Web sites. Visual Web Developer represents an evolutionary improvement in support for creating
Web sites. Visual Web Developer continues to bring you the productivity benefits of the integrated development environment
(IDE) while introducing a wide array of improvements.
The major improvements for this version of Visual Web Developer include the following:
ASP.NET 2.0 support.
Visual Web Developer supports new ASP.NET 2.0 features, including a host of new controls that are introduced in
ASP.NET 2.0. In addition, Visual Web Developer adheres closely to native ASP.NET 2.0 features and does not add
designer-specific features. For example, Visual Web Developer does not embed designer-specific tags in your
ASP.NET 2.0 pages.
More flexible project and deployment options.
Visual Web Developer allows you to create traditional Microsoft Internet Information Services (IIS) applications in the IIS
root on local and remote computers and it also supports virtual roots, opening Web sites by using File Transfer Protocol
(FTP), and using stand-alone files that reside outside a project. The end result is that it is substantially easier to create and
deploy ASP.NET 2.0 applications.
Improved code-behind model.
Visual Web Developer can create pages by using either a new code-behind model or by including code in the ASP.NET
page (the .aspx file).
Improved programming capabilities.
Many basic tasks have been greatly simplified. For example, you can create a data-bound page with no coding
whatsoever. New ASP.NET 2.0 controls add substantial functionality that used to require you to write your own code.
Microsoft IntelliSense and related technologies have been expanded to work virtually everywhere.
The following sections provide a high-level summary of the changes in Visual Web Developer.
Web Sites
Projects
Dynamic Compilation Model
Editing
Programming
Improved Code-Behind Model
Controls
Data Controls and Data Binding
Converting Existing Web Sites
Web Application Projects
For information about new features in ASP.NET 2.0, see What's New in ASP.NET.
Web Sites and Projects
Visual Web Developer features a flexible approach to creating Web sites (also called projects and Web applications in previous
versions of Visual Web Developer and the Web page designer, respectively). Web sites in Visual Web Developer are not
necessarily bound to Microsoft Internet Information Services (IIS) nor to physical folders on the IIS root.
You can now create the following types of Web sites:
File system.
You can keep all the files for a Web site in a simple folder. File-system Web sites do not depend on IIS. For details, see
Walkthrough: Creating a Basic Web Page in Visual Web Developer.
Local IIS.
As in previous versions of Visual Studio, you can create IIS applications that can reside either on the local IIS root or on a
virtual directory. You can create virtual folders, as well. For details, see Walkthrough: Basic Data Access in Web Pages.
Remote.
You can create applications residing on remote servers that support FrontPage 2002 Server Extensions from Microsoft.
This is the model that was used for previous versions of Visual Web Developer and continues to be supported in this
version.
FTP.
You can open Web sites across FTP. For details, see Walkthrough: Editing Web Sites with FTP in Visual Web Developer.
ASP.NET Development Server
The Visual Web Developer Web development tool ships with a lightweight test application server, the ASP.NET Development
Server, which you can use to test file system Web sites, without having to use IIS. For more information, see
Web Servers in Visual Web Developer.
Projects
In the new version of Visual Web Developer, Web sites are not dependent on project and solution files. You can add files to a
Web site either in Visual Web Developer or by using Microsoft Windows Explorer, and the files are automatically part of the
Web site.
Visual Web Developer still creates project and solution files to store a small amount of project-specific information, such as
your IDE settings. Much of the information that was previously stored in project files now either is stored in the Web.config file
as standard ASP.NET 2.0 configuration settings or is no longer necessary. The project file stores no information that is required
to run the application.
Working without a project model not only makes it possible to add, edit, and remove files outside of Visual Web Developer, it
also makes it easier for more than one developer to work together to create a Web site. More than one developer can add or
remove files from a Web site without requiring access to a centralized project file that needs to be updated with file
information. In addition, it is easier to keep Web site files in a source-control system, such as the Microsoft Visual SourceSafe
version control system, because developers do not have to exclusively check out a project file to add files to the Web site.
Dynamic Compilation Model
In Visual Web Developer, Web sites no longer use the compilation model that was used in previous versions, in which the
executable code for the entire project was compiled into a single assembly. Instead, by default, the new version uses the
dynamic compilation model that is native to ASP.NET 2.0.
Working with Web sites that do not produce an executable assembly as their output has a number of advantages:
You can test Web sites that contain pages still in development—pages that contain compilation errors do not prevent
other pages in the Web site from running.
For development on large Web sites, the entire application does not need to be recompiled every time a change is made
to a single page or component. When a developer changes a single page, only that page is recompiled when it is next
requested.
Different developers can make edits to different pages at the same time without interfering with one another's changes,
as could happen when compiling the project to a single assembly, as in Microsoft Visual Studio .NET 2003.
When you test a Web site, the Web site is still compiled (built). However, the compilation step is used as verification that all the
pages and their dependencies can be compiled; the output of the compilation process is not used as the basis for running the
Web site. This build step is more comprehensive than it was in earlier versions because it validates not only that the code can
be compiled but also finds errors in the markup syntax and Web.config file.
Publishing Web Sites
Because some developers do not want to deploy source code with their Web sites, the Visual Web Developer Web
development tool provides the option to precompile and deploy a Web site by using the Build Web Site command. The Build
Web Site command runs the compiler over the entire Web site (not just the code files) and produces a Web site layout that
you can deploy to a production server. The layout includes assemblies for individual pages, which include both the code and
the markup for the page (that is, the .aspx files are compiled also).
Note
This feature is not available in Visual Web Developer Express Edition.

The primary benefit of precompiling is that it allows you to deploy only executable code, thus bringing a measure of protection
to your intellectual property. In addition, precompiling finds any compile-time errors in the pages or dependent code. Finally,
precompiling improves performance and reduces the time it takes for pages in your Web site to render the first time.
Editing Pages
Visual Web Developer offers the following enhancements for creating and editing Web pages:
Support for new page features.
The Visual Web Developer Web page designer features WYSIWYG support for new ASP.NET 2.0 page elements, such as
master pages. For details, see ASP.NET Master Pages Overview and
Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer.
Preservation of source code.
Visual Web Developer maintains the HTML formatting of your page when you switch between Design and Source view
and when you save files.
Enhanced HTML generation and validation.
Visual Web Developer provides more options for generating and validating the HTML on your page. By default, the Web
page designer creates markup that is XHTML 1.1 compatible and new schemas include support for several variations of
XHTML. You can set options to determine how strictly Visual Web Developer validates the elements in your page and
HTML is also validated more strictly. Additionally, Visual Web Developer provides error information in ToolTips.
Drag-and-drop functionality in Source view.
You can drag controls from the Toolbox while in Source view.
For more information, see Walkthrough: Creating a Basic Web Page in Visual Web Developer.
Programming
Visual Web Developer includes a number of improvements to the code editor that help you code more productively, including
the following:
Microsoft IntelliSense technology.
Statement completion is now virtually everywhere when you edit Web pages. The IntelliSense technology helps you
create code in both code-behind and single-file pages, markup tags, page directives, and so on.
Event drop-down lists.
You can create event-handlers in Source view by using event drop-down lists, as you previously could do only in Code
view. The Properties window now allows you to create event handlers for both Visual Basic and C#.
Single-file page support.
The code editor now provides equivalent support for code-behind and single-file ASP.NET 2.0 pages. (For information
about changes to the code-behind model, see Improved Code-Behind Model.) Both code models support syntax
coloration, IntelliSense technology, and so on.
Shared code.
Classes for which the source code is in the App_Code folder for your Web application are automatically referenced; if you
have compiled components, you can place them in the Bin folder to have Visual Web Developer reference them
automatically. IntelliSense functionality picks up information about any components that are installed in the App_Code or
Bin folder of your application. For details, see Walkthrough: Using Shared Code in Web Sites in Visual Web Developer.
Debugging.
You have full debugging facilities for local Web sites, including file system Web sites. Debugging is less complex and
faster than in previous versions. For details, see Walkthrough: Debugging Web Pages in Visual Web Developer.

Improved Code-Behind Model


A significant difference between previous versions of Visual Web Developer and this release is in how code-behind pages
work. In Microsoft Visual Studio .NET 2002, when you created a new Web Forms page, Visual Web Developer created an .aspx
file with the markup and a separate .vb or .cs file (the code-behind file) for the page's code. The code-behind file defined a
complete class that was derived from the Page class.
The Web page designer kept the .aspx file and the code-behind file in synchronization. For example, if you added a Web server
control to the .aspx file, the Web page designer created a corresponding instance variable in the code-behind file for that
control.
In this version, the code-behind model takes advantage of a new language feature known as partial classes. The code-behind
file for a page is not a complete class definition. Instead, it includes only the application code that you need, such as event
handlers. The code-behind partial class does not need to include instance variables; ASP.NET 2.0 infers the control instances
from the markup at compile time. If you are coding in C#, you do not need to include explicit delegates for event binding,
because ASP.NET 2.0 can deduce them from the event attributes (for example, onclick) in the control markup. In Visual Basic,
you can add a Handles clause onto the declaration of an event method, as in the previous model, to bind the event to the
handler.
The new code-behind model offers a number of advantages over the previous model, as follows:
True separation of code and markup.
In previous versions, the markup and code were stored in separate files. However, because previous versions needed to
keep the files in synchronization by using instance variables and event delegates, it was not practical to work with the
files separately. For example, it was not practical for a page developer to work on the layout of the page while another
developer worked on the code. In this version, this is much more achievable.
Less complexity in referencing controls.
As noted, the new code-behind model does not require explicit instance variables in the code-behind page. Even though
previous versions managed the instance variables, it did not do so for all controls—notably for user controls or for some
HTML elements that were declared as controls. In this version, because no instance variables are required, all controls,
including user controls, are referenced implicitly.
Less generated code.
The new code-behind model contains virtually no generated code beyond the class definition itself. There are no reserved
areas in the code-behind that the editor might overwrite.

Controls
Visual Web Developer supports new ASP.NET 2.0 controls, which offer new functionality, which results in significantly greater
productivity. In addition to hosting new controls, the Web page designer includes improvements to help you work more easily
with controls. Highlights include the following:
More consistent and powerful editing model.
The overall model for working with controls is more consistent between controls and allows you to perform many more
actions without having to use the Properties window or edit the declarative syntax of a control.
Visual display of controls.
The Web page designer has improved support for rendering controls; for example, user controls are now rendered
visually in Design view.
Task-based editing.
As you work with controls, they display a Smart Tag menu (a floating, shortcut menu of tasks) for the current control.
Typical actions that are offered by task-based editing include editing templates and setting up data binding.
Template editing.
The Web page designer provides a simplified and more intuitive interface for creating and editing templates on complex
controls, such as the DataList and GridView controls.
Table editing.
It is now much easier to create and edit HTML tables in the Web page designer. For details, see
Walkthrough: Editing HTML Tables in Visual Web Developer.
Control Extensibility
You can now extend controls in powerful new ways. As before, you can create user controls and custom controls. This release
of the Visual Web Developer Web development tool provides improved support for user controls, including WYSIWYG
rendering in Design view and Properties window support.
You can extend the run-time behavior of controls by creating adapters, which define the output of the control for a specific
device or browser. At run time, ASP.NET 2.0 determines the type of device that generated the request and invokes a control
adapter to render the appropriate output for that device for a given control. By creating an adapter for a control and a specific
class of device, you can customize the output for that control for the device. Adapters are especially useful for creating custom
rendering for new devices. For more information, see Developing Adapters for ASP.NET Server Controls.
If you develop custom controls, you now have improved support for hosting your control in a Web page designer, including
the following:
Classes that allow you to add region-based editing to your controls at design time.
Support for task-based editing, so that you can define verbs (tasks) that are exposed for your control by using a shortcut
menu in the Web page designer.
Template-editing services that simplify adding support for templates in your controls.
Controls can take advantage of tool-based services for improved interaction with their hosting environment. For
example, controls have access to the page directive, the project system, and the current document.

Data Controls and Data Binding


Working with data is an important part of many ASP.NET 2.0 Web pages, and Visual Web Developer includes many
improvements to make data access easier to implement and manage. The overall goal for data binding in ASP.NET 2.0 is to be
able to accomplish a wide variety of data-binding scenarios without having to write any code at all. This version supports this
goal and extends it by providing wizards that help you configure data binding and create data components.
Data Binding with Data Source Controls
The model for binding controls on the page to data sources has been improved considerably. The data-binding model for
Microsoft Visual Studio .NET 2002 required that you add data components, such as a connection and dataset objects, on the
page. Then, you needed to write code to manage data binding to data controls, such as the DataList and DataGrid controls.
To simplify data binding, ASP.NET 2.0 introduces data source controls. Data source controls provide a single object in which
you can declaratively define the following:
Connection information.
Queries (a SQL statement, stored parameter name, or the names of methods to invoke on an object).
Parameters—you can define parameters declaratively and specify that they get their values from a control on the page,
from a query string, from session variables, or from other sources.
Behavior options (depending on the data source control), such as paging and caching.
In general, you do not need to work directly with the objects that are used to manage data access, such as datasets or data
readers. Data source controls create data components under the covers. You do not work with those components, but you do
need to be aware of them when you want to use a feature, such as paging, that depends on choosing between a dataset and a
data reader.
ASP.NET 2.0 provides data source controls for different types of data stores, including SQL (for OLE DB and Open Database
Connectivity [ODBC] databases), XML files, and business objects. All data source controls expose the same interface to data
controls on the page, so that controls, such as the DataList and Repeater controls, and the new GridView control, can bind
the same way to any data source control, regardless of the underlying data store that they represent, and then display data on
the page. The result is that you can use the full array of ASP.NET 2.0 data controls to work with a wide variety of data sources.
To help you create and configure data source controls, the Visual Web Developer Web development tool includes wizards that
help you to create connections, define queries or specify methods to call, and configure parameters.
Enhanced Data Controls
All data controls in ASP.NET 2.0 have been enhanced to work with data source controls. Instead of pointing a control at a
dataset or data reader, you reference a data source control. The data control and data source control then work together to
manage data binding automatically, so that in most cases you do not need to write code to perform data binding.
As a result, you can take advantage of automatic data binding in any data-bound control. In addition, ASP.NET 2.0 introduces
new data controls that provide additional functionality. These include the following:
The GridView control, which is the successor to the DataGrid control.
The GridView control automates many of the features of the DataGrid control, so that you do not need to write code for
editing, sorting, or paging. For situations in which you want to customize the control's behavior, you can continue to use
the object model that you are familiar with from the DataGrid control.
The DetailsView control displays one record at a time and allows you to edit, delete, and insert records.
You can also page through multiple records.
The FormView control is similar to the DetailsView control, but allows you to define a free-form layout for each record.
The FormView control is like a DataList control for a single record.
You can continue to use the DataGrid control, although it is superseded by the GridView control. Existing pages that use the
DataGrid control work as is. As with other data controls, the DataGrid control has been enhanced to interact with data source
controls.
Two-Way Data Binding
The combination of data source controls, declarative parameters, and enhanced data controls provides the ability to create
two-way data binding without having to write code. In data source controls, you can define queries or method names to use
for updates. Data controls, such as the GridView, DetailsView, and FormView controls, support edit and delete modes (and
for some controls, insert mode) that can automatically interact with the data source controls to write data to the data source.
Connection String Storage
To help make your Web sites more maintainable and more secure, you can keep connection strings in the Web.config file in a
new section that has been designed specifically for connection string storage. When you use the Visual Web Developer Web
development tool to create or configure data source controls, you can specify that the connection string be stored in the
Web.config file. If you change data sources, you can easily change the connection string in one location rather than having to
update all data components on all pages with a new connection string. For added security, you can encrypt the connection
string section of the Web.config file. For details, see Encrypting Configuration Information Using Protected Configuration.
Two-Tier and Three-Tier Data Access
The earlier data binding model encouraged the creation of two-tier data solutions, in which the Web pages interacted directly
with the database to fill a dataset and to bind controls to it. The new model continues to make it easy to work in a two-tier
structure. For example, the SqlDataSource control connects directly to a database and executes SQL statements or stored
procedures to read and write data.
The new data binding model also makes it much easier to create a three-tier structure in which data access is handled by a
middle-tier business object. The ObjectDataSource control interacts with a business object by calling methods on the object
to retrieve and update data. Data controls on the page can bind to the ObjectDataSource control as they do to other data
source controls, such as the SqlDataSource control.
The Visual Web Developer Web development tool includes a data component wizard that helps you create a custom object that
contains methods to read and update data. Alternatively, you can create your own middle-tier object that contains methods. As
long as your custom object exposes methods with the appropriate signatures, you can reference it from an ObjectDataSource
control. For details, see Walkthrough: Data Binding to a Custom Business Object.
Backward Compatibility for Data Access
The Visual Web Developer Web development tool continues to support pages that use the data binding model from previous
versions. Pages that contain datasets and other components run as they did before, and you can open them and edit the pages
in the Web page designer. Visual Web Developer does not remove the data components and does not convert the components
to data source controls.
Note
Data components, such as datasets and data connections, are not displayed in the Web page designer in Visual Web Develop
er. Therefore, you can neither set nor examine their properties by using the Properties window. However, you can still edit th
e code that is used to instantiate the data components and set their properties.

For more information, see Data Source Controls Overview and Walkthrough: Basic Data Access in Web Pages.
Converting Existing Web Sites
Visual Web Developer can automatically convert your existing projects to the new streamlined Web site layout. The conversion
process preserves the functionality of your application and the project options that apply. Existing code-behind Web pages are
converted to a new code-behind model that preserves the separation of HTML and code, but provides a simplified structure.
For more information, see Web Project Conversion from Visual Studio .NET.
After conversion, you can use the Web page designer to work with pages and controls that were developed with previous
versions of Visual Web Developer.
Web Application Projects
The new Web application project model provides the same Web project semantics as the Visual Studio .NET 2003 Web project
model. This includes a structure based on project files and a build model based on compiling all the code for a project into a
single assembly. In addition, the new project type supports many of the new features of Visual Studio 2005 (such as class
diagrams, test development, and generics) and of ASP.NET 2.0 (such as master pages, data controls, membership and logon,
role management, Web parts, personalization, site navigation, and themes).
For more information about Web application projects, see Web Application Projects Overview.
See Also
Concepts
What's New in Visual Studio 2005
Web Application Projects Overview
Other Resources
Guided Tour of Creating Web Sites in Visual Web Developer
Visual Web Developer

Community Resources for Visual Web Developer


Community is a vital part of working with Visual Web Developer. The ASP.NET and Visual Web Developer communities offer
news, information, support, and tools that help you create Web sites of your own.
This topic lists community resources that can help you work effectively with Visual Web Developer.
Site Description
ASP.NET Web site The official ASP.NET site. Includes news, tutorials, support, starter kits, and many tools for
download.

Microsoft ASP.NET Developer Center The MSDN site for ASP.NET development, a central location that brings together content
from many different sources. Includes articles, downloads, and blog feeds.

ASP.NET support forums Web site The support forums on the ASP.NET site, visited every day by thousands of knowledgeabl
e users. The site includes forums for many different aspects of ASP.NET and Visual Web
Developer, and offer assistance to both new and experienced users.

See Also
Concepts
Introduction to Visual Web Developer
Visual Web Developer

Guided Tour of Creating Web Sites in Visual Web Developer


This section contains topics designed to give a guided tour of creating Web sites in Visual Studio.
In This Section
Creating Pages
Describes how to create new ASP.NET Web sites and add ASP.NET Web pages to them. Includes information on editing
HTML, creating server code, and debugging.
Data-Driven Web Pages
Describes various ways to display and edit data in ASP.NET Web pages and explains how to optimize data access by using
caching.
Additional Page Techniques
Describes how to create specific types of ASP.NET Web pages, including master pages, Web Parts pages, and wizards. Also
includes information on creating reusable elements (user controls).
Customizing Web Pages
Describes how to add menus, define themes for consistent Web site appearance, create rotating advertisements, create
pages for browsers on mobile devices, create and use an ASP.NET Web service, and create pages that can display text in
different languages.
Building Professional Web Sites (Visual Studio), Building Professional Web Sites (Visual Web Developer Express Edition)
Describes how to use system diagnostics with ASP.NET Web pages and describes ways to deploy a Web site to a production
Web server.
Visual Web Developer

Creating Pages
The topics in this section include step-by-step walkthroughs that illustrate how to create new ASP.NET Web sites and add
ASP.NET Web pages to them. Additional walkthroughs illustrate how to edit HTML, create server code, and debug Web pages.
In This Section
Walkthrough: Creating a Basic Web Page in Visual Web Developer
Walkthrough: Creating a Basic Web Page with Code Separation in Visual Web Developer
Walkthrough: Basic HTML Editing in Visual Web Developer
Walkthrough: Working with Cascading Style Sheet Styles in Visual Web Developer
Walkthrough: Advanced HTML Editing in Visual Web Developer
Walkthrough: Code Editing in Web Pages in Visual Web Developer
Walkthrough: Debugging Web Pages in Visual Web Developer
Walkthrough: Creating a Local IIS Web Site in Visual Web Developer
Walkthrough: Editing Web Sites with FTP in Visual Web Developer
Walkthrough: Using Shared Code in Web Sites in Visual Web Developer
Related Sections
Guided Tour of Creating Web Sites in Visual Web Developer
Introduces topics that give a guided tour of creating Web sites in Visual Web Developer.
Visual Web Developer

Walkthrough: Creating a Basic Web Page in Visual Web


Developer
This walkthrough provides you with an introduction to Microsoft Visual Web Developer. It guides you through creating a
simple page by using Visual Web Developer, illustrating the basic techniques of creating a new page, adding controls, and
writing code.
Tasks illustrated in this walkthrough include:
Creating a file system Web site.
Familiarizing yourself with Visual Web Developer.
Creating a single-file ASP.NET page in Visual Web Developer.
Adding controls.
Adding event handlers.
Running pages with the Web Servers in Visual Web Developer.
Prerequisites
In order to complete this walkthrough, you will need:
Visual Web Developer
The .NET Framework
Creating a Web Site and Page
In this part of the walkthrough, you will create a Web site and add a new page to it. You will also add HTML text and run the
page in your Web browser.
For this walkthrough, you will create a file system Web site that does not require that you work with Microsoft Internet
Information Services (IIS). Instead, you will create and run your page in the local file system.
A file system Web site is one that stores pages and other files in a folder that you choose somewhere on your local computer.
Other Web site options include a local IIS Web site, which stores your files in a subfolder of the local IIS root (typically,
\Inetpub\Wwwroot\). An FTP site stores files on a remote server that you gain access to across the Internet by using File
Transfer Protocol (FTP). A remote site stores files on a remote server that you can access across a local network. For more
information, see Walkthrough: Editing Web Sites with FTP in Visual Web Developer. Also, Web site files can be stored in a
source control system such as Visual SourceSafe. For more information, see Introducing Source Control.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears, as shown in the following screen shot.
New Web Site dialog box
3. Under Visual Studio installed templates, click ASP.NET Web Site.
When you create a Web site, you specify a template. Each template creates a Web application that contains different files
and folders. In this walkthrough, you are creating a Web site based on the ASP.NET Web Site template, which creates
some folders and a few default files.
4. In the Location box, select the File System box, and then enter the name of the folder where you want to keep the pages
of your Web site.
For example, type the folder name C:\BasicWebSite.
5. In the Language list, click Visual Basic or Visual C#.
The programming language you choose will be the default for your Web site. However, you can use multiple languages
in the same Web application by creating pages and components in different programming languages.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx. When a new page is created, by default
Visual Web Developer displays the page in Source view, where you can see the page's HTML elements. The following
screen shot shows the Source view of a default Web page.
Source view of default page
A Tour of Visual Web Developer
Before you proceed with working on the page, it is useful to familiarize yourself with the Visual Web Developer development
environment. The following illustration shows you the windows and tools that are available in Visual Web Developer.
Diagram of Visual Web Developer environment

To familiarize yourself with the Web designer in Visual Web Developer


Examine the preceding illustration and match the text to the following list, which describes the most commonly used
windows and tools. (Not all windows and tools that you see are listed here, only those marked in the preceding
illustration.)
Toolbars. Provide commands for formatting text, finding text, and so on. Some toolbars are available only when
you are working in Design view.
Solution Explorer. Displays the files and folders in your Web site.
Document window. Displays the documents you are working on in tabbed windows. You can switch between
documents by clicking tabs.
Properties window. Allows you to change settings for the page, HTML elements, controls, and other objects.
View tabs. Present you with different views of the same document. Design view is a near-WYSIWYG editing
surface. Source view is the HTML editor for the page. You will work with these views later in this walkthrough. If
you prefer to open Web pages in Design view, on the Tools menu, click Options, select the HTML Designer
node, and change the Start Pages In option.
Toolbox. Provides controls and HTML elements that you can drag onto your page. Toolbox elements are grouped
by common function.
Server Explorer/Database Explorer. Displays database connections. If Server Explorer is not visible in Visual Web
Developer, on the View menu, click Other Windows, and then click Server Explorer.
Note
You can rearrange and resize the windows to suit your preferences. The View menu allows you to display addit
ional windows.

Creating a New Web Forms Page


When you create a new Web site, Visual Web Developer adds an ASP.NET page (Web Forms page) named Default.aspx. You
can use the Default.aspx page as the home page for your Web site. However, for this walkthrough, you will create and work
with a new page.
To add a page to the Web site
1. Close the Default.aspx page. To do this, right-click the tab containing the file name and select Close.
2. In Solution Explorer, right-click the Web site (for example, C:\BasicWebSite), and then click Add New Item.
3. Under Visual Studio installed templates, click Web Form.
4. In the Name box, type FirstWebPage.
5. In the Language list, choose the programming language you prefer to use (Visual Basic, C#, or J#).
When you created the Web site, you specified a default language. However, each time you create a new page or
component for your Web site, you can change the language from the default. You can use different programming
languages in the same Web site.
6. Clear the Place code in separate file check box. The following screen shot shows the Add New Item dialog box.
Add New Item dialog box

In this walkthrough, you are creating a single-file page with the code and HTML in the same page. The code for ASP.NET
pages can be located either in the page or in a separate class file. To learn more about keeping the code in a separate file,
see Walkthrough: Creating a Basic Web Page with Code Separation in Visual Web Developer.
7. Click Add.
Visual Web Developer creates the new page and opens it in Source view.
Adding HTML to the Page
In this part of the walkthrough, you will add some static text to the page.
To add text to the page
1. At the bottom of the document window, click the Design tab to switch to Design view.
Design view displays the page that you are working on in a WYSIWYG-like way. At this point, you do not have any text or
controls on the page, so the page is blank.
2. On the page, type Welcome to Visual Web Developer.
The following screen shot shows the text you typed in Design view.
Welcome text as seen in Design view

3. Switch to Source view.


You can see the HTML that you created by typing in Design view, as shown in the following screen shot.
Welcome text as seen in Source view

Running the Page


Before you proceed with adding controls to the page, you can try running it. To run a page, you need a Web server. In a
production Web site, you use IIS as your Web server. However, to test a page, you can use the ASP.NET Development Server,
which runs locally and does not require IIS. For file system Web sites, the default Web server in Visual Web Developer is the
ASP.NET Development Server.
To run the page
1. Press CTRL+F5 to run the page.
Visual Web Developer starts the ASP.NET Development Server. An icon appears on the toolbar to indicate that the Visual
Web Developer Web server is running, as shown in the following screen shot.
Visual Web Developer Web server icon

The page is displayed in the browser. Although the page you created has an extension of .aspx, it currently runs like any
HTML page.
Note
If the browser displays a 502 error or an error indicating that the page cannot be displayed, you might need to configur
e your browser to bypass proxy servers for local requests. For details, see
How to: Bypass a Proxy Server for Local Web Requests.

2. Close the browser.


Adding and Programming Controls
In this part of the walkthrough, you will add a Button, a TextBox, and a Label control to the page and write code to handle the
Click event for the Button control.
You will now add server controls to the page. Server controls, which include buttons, labels, text boxes, and other familiar
controls, provide typical form-processing capabilities for your ASP.NET Web pages. However, you can program the controls
with code that runs on the server, not the client.
To add controls to the page
1. Click the Design tab to switch to Design view.
2. Press SHIFT+ENTER a few times to make some room.
3. In the Toolbox, from the Standard group, drag three controls onto the page: a TextBox control, a Button control, and a
Label control.
4. Put the insertion point above the TextBox control, and then type Enter your name:.
This static HTML text is the caption for the TextBox control. You can mix static HTML and server controls on the same
page. The following screen shot shows how the three controls appear in Design view.
Controls in Design View

Setting Control Properties


Visual Web Developer offers you various ways to set the properties of controls on the page. In this part of the walkthrough,
you will set properties in both Design view and Source view.
To set control properties
1. Select the Button control, and then in the Properties window, set Text to Display Name, as shown in the following
screen shot.
Changed Button control text

2. Switch to Source view.


Source view displays the HTML for the page, including the elements that Visual Web Developer has created for the server
controls. Controls are declared using HTML-like syntax, except that the tags use the prefix asp: and include the attribute
runat="server".
Control properties are declared as attributes. For example, when you set the Text property for the Button control, in step
1, you were actually setting the Text attribute in the control's markup.
Note that all the controls are inside a <form> element, which also has the attribute runat="server". The
runat="server" attribute and the asp: prefix for control tags mark the controls so that they are processed by ASP.NET
on the server side when the page runs. Code outside of <form runat="server"> and <script runat="server">
elements is interpreted by the browser as client-side code, which is why the ASP.NET code must be inside.
3. Put the insertion point in a space within the <asp:label> tag, and then press SPACEBAR.
A drop-down list appears that displays the list of properties you can set for a Label control. This feature, referred to as
IntelliSense, helps you in Source view with the syntax of server controls, HTML elements, and other items on the page.
The following screen shot shows the IntelliSense drop-down list for the Label control.
IntelliSense for Label control

4. Select ForeColor and then type an equal sign (=). IntelliSense displays a list of colors.
Note
You can display an IntelliSense drop-down list at any time by pressing CTRL+J.

5. Select a color for the Label control's text.


The ForeColor attribute is completed with the color that you have selected.
Programming the Button Control
For this walkthrough, you will write code that reads the name that the user enters into the text box and then displays the name
in the Label control.
To add a default button event handler
1. Switch to Design view.
2. Double-click the Button control.
Visual Web Developer switches to Source view and creates a skeleton event handler for the Button control's default
event, the Click event.
Note
Double-clicking a control in Design view is just one of several ways you can create event handlers.

3. Inside the handler, type the following:


Label1.
Visual Web Developer displays a list of available members for the Label control, as shown in the following screen shot.
Available Label control members

4. Finish the Click event handler for the button so that it reads as shown in the following code example.
VB
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Label1.Text = Textbox1.Text & ", welcome to Visual Web Developer!"
End Sub

C#
protected void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text = TextBox1.Text + ", welcome to Visual Web Developer!";
}

5. Scroll down to the <asp:Button> element. Note that the <asp:Button> element now has the attribute
OnClick="Button1_Click". This attribute binds the button's Click event to the handler method you coded in step 4.
Event handler methods can have any name; the name you see is the default name created by Visual Web Developer. The
important point is that the name used for the OnClick attribute must match the name of a method in the page.
Note
If you are using Visual Basic with code separation, Visual Web Developer does not add an explicit OnClick attribute. Ins
tead, the event is bound to the handler method using a Handles keyword on the handler declaration itself.

Running the Page


You can now test the server controls on the page.
To run the page
1. Press CTRL+F5 to run the page in the browser.
The page again runs using the ASP.NET Development Server.
2. Enter a name into the text box and click the button.
The name you entered is displayed in the Label control. Note that when you click the button, the page is posted to the
Web server. ASP.NET then recreates the page, runs your code (in this case, the Button control's Click event handler
runs), and then sends the new page to the browser. If you watch the status bar in the browser, you can see that the page
is making a round trip to the Web server each time you click the button.
3. In the browser, view the source of the page you are running.
In the page source code, you see only ordinary HTML; you do not see the <asp:> elements that you were working with in
Source view. When the page runs, ASP.NET processes the server controls and renders HTML elements to the page that
perform the functions that represent the control. For example, the <asp:Button> control is rendered as the HTML
element <input type="submit">.
4. Close the browser.
Working with Additional Controls
In this part of the walkthrough, you will work with the Calendar control, which displays dates a month at a time. The Calendar
control is a more complex control than the button, text box, and label you have been working with and illustrates some further
capabilities of server controls.
In this section, you will add a Calendar control to the page and format it.
To add a Calendar control
1. In Visual Web Developer, switch to Design view.
2. From the Standard section of the Toolbox, drag a Calendar control onto the page:
The calendar's smart tag panel is displayed. The panel displays commands that make it easy for you to perform the most
common tasks for the selected control. The following screen shot shows the Calendar control as rendered in the Design
view.
Calendar control in Design view
3. In the smart tag panel, choose Auto Format.
The Auto Format dialog box is displayed, which allows you to select a formatting scheme for the calendar. The following
screen shot shows the Auto Format dialog box for the Calendar control.
Auto Format dialog box for the Calendar control

4. From the Select a scheme list, select Simple and then click OK.
5. Switch to Source view.
You can see the <asp:Calendar> element. This element is much longer than the elements for the simple controls you
created earlier. It also includes subelements, such as <WeekEndDayStyle>, which represent various formatting settings.
The following screen shot shows the Calendar control in Source view.
Calendar control in Source view
Programming the Calendar Control
In this section, you will program the Calendar control to display the currently selected date.
To program the Calendar control
1. From the left-hand drop-down list at the top of Source view, select Calendar1.
The drop-down list displays a list of all the objects you can write code for.
2. From the right-hand drop-down list, select SelectionChanged.
Visual Web Developer creates a skeleton event handler for the Calendar control's SelectionChanged event.
You have now seen two ways to create an event handler for a control. The first was to double-click the control in Design
view. The second is to use the drop-down lists in Source view to select an object and the event to write code for.
3. Finish the SelectionChanged event handler with the following highlighted code.
VB
Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As System.Eve
ntArgs)
Label1.Text = Calendar1.SelectedDate.ToString()
End Sub

C#
protected void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
Label1.Text = Calendar1.SelectedDate.ToString();
}

Running the Page


You can now test the calendar.
To run the page
1. Press CTRL+F5 to run the page in the browser.
2. Click a date in the calendar.
The date you clicked is displayed in the Label control.
3. In the browser, view the source code for the page.
Note that the Calendar control has been rendered to the page as a table, with each day as a <td> element containing an
<a> element.
4. Close the browser.
Next Steps
This walkthrough has illustrated the basic features of the Visual Web Developer page designer. Now that you understand how
to create and edit a Web page in Visual Web Developer, you might want to explore other features. For example, you might
want to:
Learn more about how to edit HTML in Visual Web Developer. For details, see
Walkthrough: Basic HTML Editing in Visual Web Developer.
Add data access to Web pages. For details, see Walkthrough: Basic Data Access in Web Pages.
Learn about the debugger for Web pages. For details, see Walkthrough: Debugging Web Pages in Visual Web Developer.
Create Web pages that are specifically designed for mobile phones and other devices. For details, see
Walkthrough: Creating Web Pages for Mobile Devices.
Create a consistent site layout using master pages. For details, see
Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer.
Add navigation to your site so users can easily move between pages. For details, see
Walkthrough: Adding Site Navigation to a Web Site.
See Also
Tasks
Walkthrough: Creating a Local IIS Web Site in Visual Web Developer
Walkthrough: Editing Web Sites with FTP in Visual Web Developer
Concepts
Introduction to Visual Web Developer
Other Resources
Welcome
Visual Web Developer

Walkthrough: Creating a Basic Web Page with Code Separation


in Visual Web Developer
When you create ASP.NET Web pages and write code in them, you can choose from two models for how to manage the visible
elements (controls, text) and your programming code. In the single-file model, the visible elements and code are kept together
in the same file. In the alternative model, called "code separation," the visible elements are in one file and the code is in another
file, referred to as the "code-behind" file. This walkthrough introduces you to Web pages that use code separation.
The single-file model is introduced in Walkthrough: Creating a Basic Web Page in Visual Web Developer. The walkthrough you
are reading now shows you how to create a Web page with the same functionality as the page in the single-file walkthrough,
but with a focus on using code separation.
The choice between using single-file pages and pages with code separation is primarily one of convenience and personal
preference. Working with both models in Microsoft Visual Web Developer is similar; both models have approximately equal
support in the editor. Both models have equivalent performance when the page runs. The page with code separation makes it
more practical to let a Web designer work on the layout of a page while a programmer creates the code for the page, because
the two pages can be edited separately. For more information on the differences between these models, see
ASP.NET Web Page Code Model.
Tasks illustrated in this walkthrough include:
Using Visual Web Developer to create an ASP.NET page with code separation.
Adding controls.
Adding event handlers.
Running pages with the ASP.NET Development Server.
Prerequisites
In order to complete this walkthrough, you will need:
Visual Web Developer and the .NET Framework.
Creating a Web Site and Page
In this part of the walkthrough, you will create a Web site and add a new page to it. You will also add HTML text and run the
page in your Web browser.
If you have already created a Web site in Visual Web Developer (for example, by following the steps in
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and skip to "Creating a New
Page" later in this walkthrough. Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, select File System and enter the name of the folder where you want to keep the pages of your Web
site.
For example, type the folder name C:\BasicWebSite.
5. In the Language list, click Visual Basic or Visual C#.
Note
Visual Web Developer currently does not support creating code-behind pages in Visual J#.

The programming language you choose will be the default for your Web site, but you can set the programming language
for each page individually.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating a New Page
When you create a new Web site, Visual Web Developer adds a page named Default.aspx. By default, Visual Web Developer
creates a page with code separation.
To add a page with code separation to the Web site
1. Close the Default.aspx page. To do this, right-click the tab with the file name in it and select Close.
2. In Solution Explorer, right-click the Web site (for example, C:\WebSites) and choose Add New Item.
3. Under Visual Studio installed templates, choose Web Form.
4. In the Name box, type WebPageSeparated.
5. From the Language list, choose the programming language you prefer to use (Visual Basic or C#).
6. Verify that the Place code in separate file check box is selected.
By default, this check box is selected.
7. Click Add.
Visual Web Developer creates two files. The first file, WebPageSeparated.aspx, will contain the page's text and controls,
and is opened in the editor. A second file, WebPageSeparated.aspx.vb or WebPageSeparated.aspx.cs (depending on what
programming language you selected), is the code file. You can see both files in Solution Explorer by clicking the plus sign
(+) next to the WebPageSeparated.aspx file; the code file has been created but is not open. You will open it later in the
walkthrough when you write code.
Adding HTML to the Page
In this part of the walkthrough, you will add some static HTML text to the WebPageSeparated.aspx page.
To add text to the page
1. Click the Design tab at the bottom of the document window to switch to Design view.
Design view displays the page you are working on in a WYSIWYG-like way. At this point, you do not have any text or
controls on the page, so the page is blank.
2. Type the words Welcome to Visual Web Developer Using Code Separation.
3. Switch to Source view.
You can see the HTML that you created by typing in Design view. At this stage, the page looks like an ordinary HTML
page. The only difference is in the <%@ page %> directive at the top of the page.
Adding and Programming Controls
In this part of the walkthrough, you will add a button, text box, and label control to the page and write code to handle the
button's Click event. Server controls, which include buttons, labels, text boxes, and other familiar controls, provide typical form-
processing capabilities for your ASP.NET Web pages. However, you can program the controls with code that runs on the server,
not the client.
To add controls to the page
1. Click the Design tab to switch to Design view.
2. Press ENTER a few times to make some room.
3. From the Standard group in the Toolbox, drag three controls onto the page: a TextBox control, a Button control, and a
Label control.
4. Put the insertion pointer in front of the text box and type Enter your name:.
This static HTML text is the caption for the TextBox control. You can mix static HTML and server controls on the same
page.
Setting Control Properties
Visual Web Developer offers you various ways to set the properties of controls on the page. In this part of the walkthrough,
you will work with properties in both Design view and Source view.
To set control properties
1. Select the Button control and, in the Properties window, set its Text property to Display Name.
2. Switch to Source view.
Source view displays the HTML for the page, including the elements that Visual Web Developer has created for the server
controls. Controls are declared using HTML-like syntax, except that the tags use the prefix asp: and include the attribute
runat="server".
Control properties are declared as attributes. For example, when you set the button's Text property in Step 1, you were
actually setting the Text attribute in the control's markup.
Note that all the controls are inside a <form> element that also has the attribute runat="server". The runat="server"
attribute and the asp: prefix for control tags mark the controls so that they are processed by ASP.NET when the page
runs.
Programming the Button Control
For this walkthrough, you will write code that reads the name that the user enters in the text box and then displays it in the
Label control.
To add a default button event handler
1. Switch to Design view
2. Double-click the Button control.
Visual Web Developer opens the WebPageSeparated.aspx.vb or WebPageSeparated.aspx.cs file in a separate window in
the editor. The file contains a skeleton Click event handler for the button.
3. Complete the Click event handler by adding the following highlighted code.
VB
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Label1.Text = Textbox1.Text & ", welcome to Visual Web Developer!"
End Sub

C#
protected void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text = TextBox1.Text + ", welcome to Visual Web Developer!";
}

Notice that as you type, IntelliSense helps you with context-sensitive choices. This is identical to the behavior when you
are coding in a single-file page.
Examining the Page and Code File
You now have two files that make up the complete WebPageSeparated page: WebPageSeparated.aspx and
WebPageSeparated.aspx.vb or WebPageSeparated.aspx.cs. In this section of the walkthrough, you will examine how these files
are structured and how they relate to each other.
To examine the page and code file
1. Click the WebPageSeparated.aspx tab at the top of the editor window to switch to the page file.
2. Switch to Source view.
At the top of the page is an @ page directive that binds this page to the code file. The directive looks like the following
code.
VB
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="WebPageSeparated.aspx.vb" Inh
erits="WebPageSeparated" %>

C#
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebPageSeparated.aspx.cs" Inhe
rits="WebPageSeparated" %>

(The line does not wrap in the editor, and the language attribute and file name extensions will match the programming
language you selected.)
When the page runs, ASP.NET dynamically creates an instance of a class representing the page. The Inherits attribute
identifies the class defined in the code-behind file from which the .aspx page is derived. By default, Visual Web Developer
uses the page name as the basis for the class name in the code-behind file.
The CodeFile attribute identifies the code file for this page. In simple terms, the code-behind file contains the event-
handling code for your page.
3. Click the WebPageSeparated.aspx.vb or WebPageSeparated.aspx.cs tab to switch to the code file.
The code file contains code that is similar to a class definition. However, it is not a complete class definition; instead, it is a
"partial class" that contains only a portion of the complete class that will make up the page. Specifically, the partial class
defined in the code file contains the event handlers and other custom code that you write. At run time, ASP.NET
generates another partial class containing your user code. This complete class is then used as the base class that is used
to render the page. For more information, see ASP.NET Page Class Overview.
Note
If you are familiar with the code-behind model used in Microsoft Visual Studio .NET 2003, you will notice that in the ne
w model, the code-behind class does not contain any generated code beyond the class definition itself. For example, th
e class does not contain instance variables for controls on the page. This type of generated code is no longer required.

Running the Page


You can now test the page.
To run the page
1. Press CTRL+F5 to run the page in the browser.
The page runs using the ASP.NET Development Server.
Note
If the browser displays a 502 error or an error indicating that the page cannot be displayed, you might need to configur
e your browser to bypass proxy servers for local requests. For details, see
How to: Bypass a Proxy Server for Local Web Requests.

2. Enter a name in the text box and click the button.


The name you entered is displayed in the Label control.
3. In the browser, view the source of the page you are running.
4. Close the browser.
The page works exactly the same as it would if it were a single-file page. (If you followed the steps in
Walkthrough: Creating a Basic Web Page in Visual Web Developer to create a single-file page, you can compare the two
pages to see that they are the same when running.)
Next Steps
This walkthrough has illustrated how to create and edit a Web page that uses code separation. From the perspective of creating
and running the page, there is not a significant difference between a single-file page and a page with code separation.
You might want to explore other features. For example, you might want to:
Create different types of Web sites. In addition to creating a file-system Web site as you did in this walkthrough, you can
work with Web sites using Microsoft Internet Information Services (IIS), SharePoint, and FTP. For details, see
Types of Web Sites in Visual Web Developer.
Learn more about how to edit HTML in Visual Web Developer. For details, see
Walkthrough: Basic HTML Editing in Visual Web Developer.
Add data access to Web pages. For details, see Walkthrough: Basic Data Access in Web Pages.
Learn about the debugger for Web pages. For details, see Walkthrough: Debugging Web Pages in Visual Web Developer.
Create a consistent site layout using master pages. For details, see
Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer.
See Also
Tasks
Walkthrough: Creating a Basic Web Page in Visual Web Developer
Concepts
Types of Web Sites in Visual Web Developer
Visual Web Developer

Walkthrough: Basic HTML Editing in Visual Web Developer


The Microsoft Visual Web Developer Web development tool provides a rich HTML editing experience that lets you work in
WYSIWYG mode for visualizing Web pages and also lets you work directly with HTML markup for finer control. This
walkthrough introduces you to the HTML editing features of Visual Web Developer.
Tasks illustrated in this walkthrough include the following:
Creating and editing HTML in Design view.
Creating and editing HTML in Source view.
Using navigation tools to move quickly through your HTML tags.
Prerequisites
In order to complete this walkthrough, you will need the following:
A general understanding of Visual Web Developer.
For an introduction to creating Web pages in Visual Web Developer, see
Walkthrough: Creating a Basic Web Page in Visual Web Developer.
In this walkthrough, you will work with a Web site and a single ASP.NET Web page that is similar to the one that is created in
Walkthrough: Creating a Basic Web Page in Visual Web Developer. If you have completed that walkthrough, you can use that
Web site and page.
Creating the Web Site and Page
If you have already created a Web site in Visual Web Developer (for example, by completing
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and go to the next section.
Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of the Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language that you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Working in Design View
In this part of the walkthrough, you will learn how to work in Design view, which provides a WYSIWYG-like view of the page.
You can add text by typing, as you would in a word processing program. You can format text directly with formatting
commands or by creating in-line styles.
Design view displays your page in a way that is similar to how it will appear in a browser, with some differences. The first
difference is that in Design view, the text and elements are editable. The second difference is that to help you edit your pages,
Design view displays some elements and controls that will not appear in the browser. Additionally, some elements, such as
HTML tables, have a special Design view rendering that adds additional space for the editor. Overall, Design view helps you
visualize your page, but it is not an exact representation of how the page will render in a browser.
To add and format static HTML in Design view
1. If you are not in Design view, click Design, which is located at the lower left of the window.
2. At the top of the page, type ASP.NET Web Page.
3. Highlight the text to format to select it, and then on the Format toolbar, in the left-most list, click Heading 1.
4. Position the insertion pointer below ASP.NET Web Page, and then type This page is powered by ASP.NET.
5. Right-click This page is powered by ASP.NET., and then click Style.
The Style Builder dialog box appears.
6. Click Font, and then in Family, click the ellipsis (…) button.
The Font Picker dialog box appears.
7. Under Installed fonts, click Verdana, and then click the add (>>) button.
8. Click OK to close the Font Picker dialog box.
9. Click Text, and then in the Horizontal list, click Centered.
10. Click OK.
Viewing Tag Information
When you are working in Design view, you might find it useful to see the design surface tags, such as div and span, and others
that do not have a visual rendering.
To see HTML design surface tags in Design view
On the View menu, click Details.
The designer displays symbols for paragraphs, line breaks, and other tags that do not render text.
Adding Controls and Elements
In Design view, you can drag controls from the Toolbox onto the page. You can add some elements, such as HTML tables, using
a dialog box. In this section, you will add some controls and a table so that you have elements to work with later in the
walkthrough.
To add controls and a table
1. Position the insertion pointer to the right of the closing paragraph mark for This page is powered by ASP.NET., and
then press ENTER.
2. From the Standard group in the Toolbox, drag a TextBox control onto the page.
Note
You can also add a control by double-clicking it.

3. Drag a Button control onto the page.


The TextBox and Button controls are ASP.NET Web server controls, not HTML elements.
4. On the Layout menu, click Insert Table.
The Insert Table dialog box appears.
5. Click OK.
The Insert Table dialog box provides options for configuring the table that you are creating. However, for this
walkthrough, you can use a default table layout.
Creating Hyperlinks
Design view provides builders and other tools to help you create HTML elements that require property settings.
To create a hyperlink
1. In the text This page is powered by ASP.NET., highlight ASP.NET to select it.
2. On the Format menu, click Convert to Hyperlink.
The Hyperlink dialog box appears.
3. In the URL box, type http://www.asp.net.
4. Click OK.
Setting Properties in the Properties Window
You can change the look and behavior of the elements on the page by setting values in Properties.
To set properties by using the Properties window
1. Click the Button control that you added in "Adding Controls and Elements," earlier in this walkthrough.
2. In Properties, set Text to Click Here, ForeColor to a different color, and Bold to true.
3. Place the insertion point in the ASP.NET hyperlink that you created in the preceding section.
Notice that in Properties, the HRef property for the a element is set to the URL that you provided for the hyperlink.
Testing the Page
You can see the results of your editing by viewing the page in the browser.
To start the page in the browser externally
Right-click the page, and then click View in Browser.
If you are prompted to save your changes, click Yes.
Visual Web Developer starts the Visual Web Developer Web server, which is a local Web server that you can use to test
pages without using IIS.
Changing the Default View
By default, Visual Web Developer opens new pages in Source view.
To change the default page view to Design view
1. On the Tools menu, click Options
2. In the Options dialog box, click HTML Designer, and then under Start Pages in, click Design view.
Note
You can run pages in several ways. If you press CTRL+F5, Visual Web Developer performs the start action that is configured
on the property page for Start Options. The default start option for CTRL+F5 is to run the current page; that is, the page that
is currently active in Source or Design view. You can also run pages in the debugger. For more information, see
Walkthrough: Debugging Web Pages in Visual Web Developer.

Working in Source View


Source view lets you edit the markup of the page directly. The Source view editor gives you many features that help you as you
create HTML and ASP.NET controls. You can use the Toolbox in Source view just as you do in Design view to add new elements
to the page.
To add elements in Source view
1. Switch to Source view by clicking Source, which is located at the lower left of the window.
The controls that you have added are created as <asp:> elements. For example, the Button control is the <asp:button>
element. The property settings that you made are preserved as attribute settings in the <asp:button> tag.
2. From the HTML group in the Toolbox (not the Standard group), drag a Table control onto the page and place it just
above the closing </form> tag.
The editor also helps you when you type markup manually. For example, the editor provides context sensitive choices finishing
HTML tags and attributes as you type. The editor also provides error and warning information on markup by underlining
questionable markup with a wavy line. The error or warning information is available by positioning the mouse over the
markup text.
To edit HTML in Source view
1. Position the insertion point above the closing </form> tag, and then type a left angle bracket (<).
Notice that the editor offers you a list of tags that are appropriate in the current context.
2. Highlight a to select it, and then press the SPACEBAR.
The editor displays a list of attributes that are appropriate for an anchor tag.
3. In the list, click href, and then type an equal sign and a double quotation mark (=").
The editor offers you a list of currently available pages to link to and an option to open the Homepicker dialog box.
4. In file list, double-click Default.aspx, press the SPACEBAR, and then type a right angle bracket (>) to close the tag.
The editor inserts a closing </a> tag.
5. Finish the anchor element so that it links to the Default.aspx page using the link text Home and reads as follows:

<a href="Default.aspx">Home</a>

6. Position the insertion point in the a tag.


Notice that Properties displays the attributes for the tag.
7. In Properties, for the HRef property, click the ellipsis (…) button.
The Select Project Item dialog box appears.
Now, you can select a page in the current Web site as the target page. If you do not have other pages in the Web site to
choose from, close the Select Project Item dialog box and type a favorite URL into the Href box of the Properties
window.
8. Position the insertion point just above the closing </form> tag, and then type <invalid>.
The editor underlines the tag with a wavy line, indicating that the tag is not a recognized HTML tag.
9. Remove the tag that you created in the preceding step.
Examining HTML Formatting
An important feature of the page designer is that it preserves the HTML formatting that you apply to the page unless you
explicitly specify that the editor reformat the document.
To examine HTML formatting
1. Reformat the attributes for the Button control by aligning the attributes so that the declarative syntax looks like the
following:

<asp:Button
id="Button1"
runat="server"
Font-Bold="True"
ForeColor="Blue"
Text="Click Here" />

Notice that after you indent the first attribute, if you press ENTER in the tag, subsequent lines are indented to match.
2. Switch to Design view.
3. Right-click the new Button control, and then click Copy.
4. Position the insertion point below the new Button control, right-click, and then click Paste.
This creates a button with the ID of Button2.
5. From the Standard group in the Toolbox, drag a third Button control onto the page, which creates <Button3>.
6. Switch to Source view.
Notice that <Button2> is formatted exactly the way that you formatted <Button1>. On the other hand, <Button3> is
formatted using the default formatting for asp:button elements.
Note
For more information on how to customize the formatting of individual elements, see
Walkthrough: Advanced HTML Editing in Visual Web Developer.

7. Edit the document so that <Button1> and <Button2> are on the same line without a space between them:

<asp:Button ID="Button1" runat="server" Font-Bold="True"


ForeColor="Blue" Text="Click Here" /><asp:Button ID="Button2"
runat="server" Font-Bold="True" ForeColor="Blue" Text="Click Here"/>

The elements can wrap, but the end of <Button1> (that is, />) must be followed immediately by the beginning of
<Button2> (that is <asp:Button ID=).

8. Switch to Design view.


Notice that <Button1> and <Button2> are right next to each other without a space between them.
9. Switch to Source view
10. On the Edit menu, point to Advanced, and then click Format Document.
The document is reformatted, but <Button1> and <Button2> remain on the same line. If the editor were to separate the
buttons, it would introduce a space during rendering. Therefore, the editor does not change the formatting that you have
created.
Navigating Between Elements
As pages become larger and more complex, it is useful to be able to find tags quickly and to reduce the clutter in the page.
Visual Web Developer provides the following tools to help you with these tasks when you are working in Source view:
Document Outline, which provides a complete view of the document.
Tag navigator, which provides information about the currently selected tag and where it is in the page hierarchy.
To start, add more elements to the page so that you will be able to examine navigation features.
To add elements
1. Switch to Design view.
2. From the HTML group in the Toolbox, drag a Table control into a cell of the table that you created in "Working in Source
View," earlier in this walkthrough.
3. From the Standard group in the Toolbox, drag a Button control into the middle cell of the nested table.
With several nested elements on the page, you can see how Document Outline provides quick navigation to any tag in the
page.
To navigate with Document Outline
1. Switch to Source view.
2. On the View menu, point to Other Windows, and then click Document Outline.
3. In Document Outline, click Button4.
In the editor, the <Button4> control that you added in the preceding procedure is selected.
4. Right-click the <table> tag of the outer table, and then click Synchronize Document Outline.
The selection in Document Outline is moved to the outer table tag.
The tag navigator provides information about the currently selected tag and where it is in the page hierarchy.
To navigate with tag navigator
1. Position the insertion point in the <asp:button> tag.
Notice the tag navigator at the bottom of the window, which shows the <asp:button> tag and its parent tags. The tag
navigator includes the ID of the element, if any, so that you can identify which element is being displayed. The tag
navigator also displays the assigned cascading style sheet, if any, that was set with the Class attribute.
2. In the tag navigator, click the <table> tag that is closest to the <asp:button#Button4> tag.
The tag navigator moves to the inner <table> element and selects it.
3. In the tag navigator, click the <td> tag to the left of the selected <table>.
The whole cell that contains the nested table is selected.
Note
You can click to select either the tag or its contents by using the drop-down list in the tag navigator tag. By default, click
ing a tag in the tag navigator selects the tag and its contents.

You can also use the tag navigator to help you move or copy elements.
To move or copy elements using the tag navigator
1. Using the tag navigator, select the <tr> tag that contains <Button4>.
2. Press CTRL+C to copy the tag.
3. Use the tag navigator to move to the outer table.
4. In Source view, place the insertion pointer between the <table> tag and the first <tr> tag.
5. Press CTRL+V to paste the copied row into the table.
6. Switch to Design view.
Notice that the new row has been added, including a Button control.
Formatting Text
The Formatting toolbar applies inline styles for most settings. Bold and italic formatting is applied by using the b and i
tags. Paragraph formatting is applied a block tag, such as p (for normal), pre (for formatted), and so on. Paragraph
alignment is applied by using inline styles to conform with XHTML 1.1 standards.
The designer also lets you create a style block and a link to a cascading style sheet. For more information, see
Walkthrough: Working with Cascading Style Sheet Styles in Visual Web Developer.
By default, the editor creates markup that is compatible with the XHTML 1.1 standard and converts all HTML tag names
to lowercase, even if you type them in uppercase. The editor also encloses attribute (property) values in quotation marks.
For more information, see Walkthrough: Advanced HTML Editing in Visual Web Developer.

To change the default markup validation


1. In Source view, right-click the page, and then click Formatting and Validation.
2. In the Options dialog box, expand Text Editor, expand HTML, and then click Validation.
3. In the Target list, enter a validation type.
Next Steps
This walkthrough has given you an overview of the HTML capabilities of the Web page editor. This includes how to create
HTML in Design view and Source view, basic formatting, and navigation. You might want to learn more about the editing
facilities in Visual Web Developer. For example, you might want to do the following:
Learn about the additional capabilities of the HTML editor, including custom formatting options, outlining, and HTML
validation. For more information, see Walkthrough: Advanced HTML Editing in Visual Web Developer.
Learn how to work with cascading style sheet styles. For more information, see
Walkthrough: Working with Cascading Style Sheet Styles in Visual Web Developer .
See Also
Tasks
Walkthrough: Advanced HTML Editing in Visual Web Developer
Reference
Source View
Concepts
Design View
Visual Web Developer

Walkthrough: Working with Cascading Style Sheet Styles in


Visual Web Developer
The Visual Web Developer Web development tool gives you complete support for creating and applying styles to the text,
elements, and controls on Web pages.
Tasks illustrated in this walkthrough include the following:
Setting inline styles for individual elements.
Creating a style block for a page.
Creating a cascading style sheet (.css file), and then applying the .css file to one or more pages in your site.
Changing style sheet references programmatically.
Note
In addition to explicitly setting styles and style sheet references in a page, you can use ASP.NET themes to set the overal
l appearance of the pages in your site. For more information, see ASP.NET Themes and Skins Overview.

Prerequisites
In order to complete this walkthrough, you will need the following:
Visual Web Developer and the .NET Framework.
A general understanding of working in Microsoft Visual Studio.
For an introduction to Visual Studio, see Walkthrough: Creating a Basic Web Page in Visual Web Developer.
Creating the Web Site and Page
In the first part of the walkthrough, you will create a Web site and a page where you can work with styles.
If you have already created a Web site in Visual Studio by completing
Walkthrough: Creating a Basic Web Page in Visual Web Developer, you can use that Web site and go to the next section.
Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. In the Language list, click the programming language that you prefer to work in.
The programming language that you choose will be the default for the Web site, but you can set the programming
language for each page individually.
4. Under Visual Studio installed templates, click ASP.NET Web Site.
5. In the right-most Location box, type the name of the folder where you want to keep the pages of the Web site.
For example, type the folder name C:\WebSites.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Adding Controls
The next step is to add some controls to the page. The code will be simple, but enough to let you add breakpoints later.
To add controls
1. Switch to Design view.
2. From the Standard group in the Toolbox, drag the following controls onto the page and set their properties as shown.

a. Control a. Properties

Label ID: CaptionLabel


Text: (empty)

TextBox ID: NumberTextbox


Text: (empty)

Button ID: SquareButton


Text: Square

Label ID: ResultLabel


Text: (empty)
Note
For this walkthrough, the layout of the page is not important.

Setting Inline Styles


You set inline styles when you want to apply formatting to a single element on the page. Visual Web Developer gives you a
rich editor for editing inline styles for elements on the page. In this section of the walkthrough, you will set styles in both
Design view and Source view.
To set inline styles in Design view
1. Switch to Design view.
2. Right-click CaptionLabel, and then click Style.
The Style Builder dialog box appears.
The Style Builder helps you set style information by organizing style information into logical categories and offering
you appropriate values and options for each style setting.
3. Click Font, click Family, and then click the ellipsis (...) that is located to the right of the text box.
The Font Picker dialog box appears.
Under Installed fonts, click Arial, and then click add (>>).
Arial appears under Selected fonts.
4. Repeat the preceding step to add Times New Roman and Verdana to the list of selected fonts, and then click OK.
When you return to the Style Builder dialog box, the three font names are in the Family box. You have created the list
of fonts that will be used to render the contents of the Label control in order of preference.
5. Under Size, click Specific, in the box, type 1.2, and then in the list, enter em.
By setting the size to 1.2 ems, you are indicating that the text will appear 1.2 times larger than the current font size
setting in the user's browser. At the bottom of the dialog box, you can see a preview of what the text will look similar to.
6. Click Background, click the ellipsis (…) that is located to the right of the Color box, and in the Color Picker dialog box,
click a color.
7. Click OK to close the Style Builder dialog box.
The text in the label now reflects the style settings that you made.
From these few steps, you can see that the Style Builder lets you set any inline style for any element without requiring that you
know the syntax.
If you prefer working directly with HTML, you can also set styles in Source view.
To set inline styles in Source view
1. Switch to Source view.
The <asp:label> element for the CaptionLabel control now has a style attribute that reflects the settings that you
made in the Style Builder.
2. Position the insertion pointer on a space in the <asp:button> element, and then type style=.
Note
The editor always puts quotation marks around the style attribute, regardless of the formatting options that you have s
et. For more information, see Walkthrough: Advanced HTML Editing in Visual Web Developer.

3. Double-click background-color, and then type a colon (:).


Microsoft IntelliSense functionality displays a list of color names. A ToolTip displays the syntax for the background-
color style setting.
4. Double-click Blue, type a semicolon (;), which is the delimiter between style settings, and then press SPACEBAR to
display IntelliSense functionality.
5. Double-click color, type a colon (:), and then double-click a contrasting color, such as Yellow or White.
6. To see the effect of your choices, switch to Design view.
Creating and Applying a CSS Style Sheet
Besides setting inline styles for individual elements, you can also create and apply cascading style sheet (CSS) files. A cascading
style sheet lets you define styles that can be applied to multiple controls and pages without having to edit elements
individually.
In this section of the walkthrough, you will create a style sheet, which lets you use the same tools that you used to set inline
styles. You will then apply the style sheet to the page that you have been editing.
To create a style sheet
1. In Solution Explorer, right-click the name of the Web site (for example, C:\WebSites), and then click Add New Item.
2. Under Visual Studio installed templates, click Style Sheet.
3. In the Name box, type dark.css, and then click Add.
The editor opens with a new style sheet that contains a body style element.
4. Position the insertion pointer between the opening and closing braces ({ }), and then on the Styles menu, click Build
Style.
The Style Builder - body dialog box appears.
5. Click Font, under Font Attributes, click the ellipsis (…) that is located to the right Color box, in the Color Picker dialog
box, click a light color, and then click OK.
Note
Be sure to select a color that is different from the default color of the pages in the Web site.

6. Click Background, click a dark color, such as Maroon, that contrasts with the font color you selected in the preceding
step, and then click OK to close the Style Builder- body dialog box.
7. Position the insertion pointer after the closing brace of the body element, right-click, and then click Add Style Rule.
The Add Style Rule dialog box appears.
The Add Style Rule dialog box lets you create new styles that are bound to a particular HTML element type, to a style
class name, or to a specific element.
8. Click Class name, and then in the box, type reverse.
This will create a new style class named reverse. You will be able to apply the style settings that you defined for the
reverse class to any element on your page. You could optionally create the class so that it applies to only specific types of
elements (anchors, buttons, and so on), but in this walkthrough you will create a simple style class.
9. Click OK to close the Add Style Rule dialog box.
10. Use the style builder or IntelliSense functionality to set the colors for the reverse style to the opposite of the styles for
the body. The element will look similar to the following:

.reverse
{
background-color:white;
color:maroon;
}

Now that you have a style sheet, you can reference it in the page you have been editing.
To reference the style sheet on the Web page
1. Open Default.aspx page and switch to Design view.
2. From Solution Explorer, drag the dark.css file onto the page.
The page is updated, displaying the effect of the style sheet.
3. Click ResultLabel, and then in Properties, set CssClass reverse.
This applies the reverse style to ResultLabel.
4. Switch to Source view.
In the <head> element, you can see that the editor has added a <link> element that references the style sheet. You can
also see that the cssclass attribute of the second <asp:label> element has been set to reverse.
5. Right-click the page, and then click View in Browser.
The page appears in the browser with the style sheet applied.
Changing Style Sheets Programmatically
Sometimes, you might want to be able to dynamically change the style sheet that is referenced by a page. In this part of the
walkthrough, you will create a second style sheet, and then in your page, write several lines of code that switch style sheets
programmatically.
To create a new style sheet
1. In Solution Explorer, right-click the Web site name, and then click Add New Item.
2. Under Visual Studio installed templates, click Style Sheet, in the Name box, type light.css, and then click Add.
3. In the new style sheet, use the Style Builder or IntelliSense functionality to create the following styles:

body
{
background-color:white;
color:Black;
}
.reverse
{
background-color:Black;
color:White;
}

4. Save the new style sheet.


In your original page, you can now add the ability to switch style sheets. You will add two radio buttons that let the user select
between a dark look and a light look.
To let users change style sheets
1. Open the Default.aspx page and switch to Source view.
2. In the <link> element, which is in the <head> element, add the attribute ID="stylesheet".
The tag will look similar to the following:

<link href="dark.css" type="text/css" rel="stylesheet" id="stylesheet" />

Adding these two attributes makes the <link> element a server control that you can program using server-based code.
3. Switch to Design view, and then from the Standard group in the Toolbox, drag two RadioButton controls onto the
page.
Note
The layout of the RadioButton controls is not important for this walkthrough.

4. Set the following properties for the RadioButton controls.

a. Control a. Properties

RadioButton1 ID: radioDark


AutoPostBack: true
Checked: true
GroupName: grpSelectStylesheet
Text: Dark

RadioButton2 ID: radioLight


AutoPostBack: true
Checked: false
GroupName: grpSelectStylesheet
Text: Light

5. Click radioDark and on the Properties toolbar, click the events icon to display available events.
6. In the CheckedChanged box, type SwitchStylesheets, and then press ENTER.
The editor creates a handler for the CheckedChanged event of the radioDark control.
7. Type or copy the following code, which switches the Href attribute of the <link>.
VB
Protected Sub SwitchStylesheets(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles radioDark.CheckedChanged
If radioDark.Checked Then
stylesheet.Href = "dark.css"
ElseIf radioLight.Checked Then
stylesheet.Href = "light.css"
End If
End Sub

C#
protected void SwitchStylesheets(Object sender, EventArgs e)
{
if (radioDark.Checked)
stylesheet.Href = "dark.css";
if (radioLight.Checked)
stylesheet.Href = "light.css";
}

The code determines which option button is selected and sets the Href attribute of the <link> element, which you
named stylesheet, appropriately.
8. Switch to Design view.
9. Click radioLight, and in Properties, click the events icon.
10. In the CheckedChanged box, click SwitchStylesheets.
This binds the CheckedChanged event of the radioLight control to the handler that you have already written to switch
style sheets. Both radio buttons will call the same handler when they are clicked.
You can now test your page.
To test the page
1. Press Ctrl+F5 to run the page.
2. Click Light.
The appearance of the page changes.
3. Click Dark to make sure that both option buttons work.
Next Steps
This walkthrough has illustrated the basic techniques for working with CSS styles in your ASP.NET Web pages. You might also
want to explore the following ways you can control the appearance of the Web pages:
Setting style information programmatically for HTML elements.
For more information, see How to: Set HTML Server Control Properties Programmatically.
Creating styles programmatically and applying the styles to ASP.NET server controls.
Creating themes and skins, which let you specify not only CSS styles, but virtually any property of an ASP.NET control.
For details, see ASP.NET Themes and Skins Overview.
Visual Web Developer

Walkthrough: Advanced HTML Editing in Visual Web


Developer
The Microsoft Visual Web Developer Web development tool provides a rich HTML editing experience for creating Web pages.
This walkthrough introduces some of the more advanced HTML editing features of Visual Web Developer.
Note
For an introduction to HTML editing, see Walkthrough: Basic HTML Editing in Visual Web Developer.

Tasks illustrated in this walkthrough include the following:


Specifying options for how the HTML editor formats elements in the page.
Selecting options so that the HTML editor that you create is compatible with specific browsers.
Outlining your page — that is, creating collapsible regions in the editor to reduce clutter.
Prerequisites
In order to complete this walkthrough, you will need:
A general understanding of working in Visual Web Developer.
For an introduction to Visual Web Developer, see Walkthrough: Basic HTML Editing in Visual Web Developer.
Creating the Web Site and Page
If you have already created a Web site in Visual Web Developer (by completing
Walkthrough: Basic HTML Editing in Visual Web Developer), go to the next section. Otherwise, create a new Web site and page
by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of the Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language that you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Note
By default, Visual Web Developer creates ASP.NET Web pages using the code-behind model. For more information, see
ASP.NET Web Page Code Model. In this walkthrough, you will not be using the code-behind page.

Formatting Markup
The HTML editor provides a variety of options to help you format the markup in your pages according to your own
preferences. Formatting options include the following:
Whether tag and attribute names are in uppercase or lowercase letters. You can specify options separately for HTML tags
and ASP.NET Web server controls.
Whether attributes are added by enclosing them in quotation marks.
Whether elements are closed automatically by the editor. Choices include creating self-closing tags (for example, <br />),
creating opening and closing tags (<p></p>), and automatically inserting closing tags.
How child elements of a tag are indented.
Where line breaks are positioned around tags.
Regardless of what formatting options you set, an important feature of HTML formatting is that you have ultimate control over
the layout and appearance of the markup in the page. You can format elements manually (for example, by indenting them),
and the editor leaves your formatting as is unless you explicitly make a request to have the markup reformatted.
In this part of the walkthrough, you will explore different formatting options and see the effect of different settings. You will
also learn how to apply formatting to the whole page or to a selection within the page.
Note
This walkthrough reviews only the formatting features that are unique to working with HTML. As a Visual Web Developer tex
t editor, the HTML editor also supports various options that apply to all text editing, such as setting tab size and line wrap. For
information about general text editing options, see Editing Text, Code, and Markup.

In this part of the walkthrough, you will add some simple HTML to the page, change formatting options, and then add more
HTML. This illustrates how changing the settings affects how the HTML is formatted.
To add HTML elements that have default formatting options
1. Switch to Design view.
2. On the Layout menu, click Insert Table, and then click OK.
Do not change any one of the default settings in the dialog box.
The designer creates an HTML table with three columns and three rows.
3. Below the table, click the page.
4. Press ENTER several times to create some blank space, and then from the HTML group in the Toolbox, drag an Image
control onto the page.
5. Switch to Source view.
You will see that the <table> and <img> elements have been inserted in the page.
By default, the designer creates elements in which the tag and attribute names are lowercase and attributes are enclosed
in quotation marks.
You can now change the formatting options.
To change formatting and validation options
1. On the Tools menu, click Options.
2. Click Validation, and then in the Target list, click Internet Explorer 6.0.
3. Click Format.
You can set some options separately for server tags (ASP.NET server controls) and client tags (HTML elements).
4. In the Client tag list, click Uppercase.
5. Clear the Insert attribute value quotes when formatting and Insert attribute value quotes when typing check
boxes.
6. Click OK to return the editor.
Notice that although you changed formatting options, the existing markup in the page does not change.
You can now add new elements.
To add HTML elements using the new formatting options
1. Scroll to the bottom of the page.
2. From the HTML group in the Toolbox, drag a Table control onto the page and position it above the </form> tag.
This time, the tags in the <TABLE> element are in uppercase letters.
3. Below the table that you just created, position the insertion point, and then type a right angle bracket (<) to start a new
tag.
A list appears in which all the tag names are offered in uppercase, because that is the option that you have set for
formatting.
4. In the list, double-click IMG, and then press the SPACEBAR.
A list of attributes for the <img> tag appears. The attributes are in lowercase, because when you set formatting options,
you left Client attributes as the default setting for Lowercase.
5. In Properties, set Src to graphic.gif, which is an invented graphic file name, and make sure that the tag now looks
similar to the following:

<IMG src=graphic.gif

Because you disable the Insert attribute value quotes when typing option in the preceding procedure, the editor does
not automatically enclose the attribute in quotation marks.
Note
The editor inserts quotation marks, regardless of the options setting, if the attribute requires them, such as when an att
ribute value contains a space.

6. Type a slash mark (/) and a right angle bracket (>) to close the <img> tag.
As noted earlier in this section, the formatting options that you set were not applied to existing markup in the page. However, if
you want, you can apply formatting settings to the page or to individual elements in the page.
To apply formatting to existing elements
1. In Source view, highlight to select the first table that you created.
2. On the Edit menu, click Format Selection.
The tag names are changed to uppercase.
Note
The editor does not remove quotation marks, even if you change the option setting. Similarly, the editor does not chan
ge the termination of existing tags, even if you change the option for how to close tags.

You can see from this example how formatting works in the HTML editor. When you use editing tools, such as Toolbox or
Properties, to edit elements, the editor uses the current set of formatting options to generate the markup. However, the editor
does not change any existing markup. If you want to apply new formatting options to existing markup, you can apply it
manually by using the Edit menu commands.
Setting Tag Formatting Options
The formatting options that you have worked with up to this point apply to all elements in the page. If you want, you can
specify formatting options for individual tags also. This is useful if you frequently use certain tags and want to use non-default
formatting for those tags. Per-tag formatting lets you set the following formatting options:
How the tags are closed—that is, not closed, self-terminated, or with a separate closing tag.
How line breaks are used around and within tags.
How child elements of a tag are indented.
Note
Tag-specific formatting rules that you specify can be overridden by the rule that the HTML editor will not change the re
ndering of tags. If a tag formatting rule would change the way a tag is rendered, the rule is ignored.

In this part of the walkthrough, you will set several tag formatting options and see how the editor works with them. Up to this
point, you have worked with HTML elements, such as the <table> element. Now, you will work with some ASP.NET server
controls, so that you can see that formatting options apply equally to controls and elements.
You will start by setting some options that apply to all tags of a certain type. You can set options for the following types of
elements:
HTML elements that do not have content, such as br and input.
HTML elements that can have content, such as table and span.
Server elements (asp:) that cannot have content, such as asp:image.
Server elements that can have content, such as asp:textbox.
Security Note
A TextBox control accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user in
put does not include script or HTML elements. For more information, see Script Exploits Overview.

For the first part of this section, you will add an HTML table. You will then change the tag formatting rules for table elements
and reformat the document to see the effect of changing the formatting rule.
To set tag-formatting rules for an HTML table
1. In Source view, in a blank part of the window, right-click, and then click Formatting and Validation.
The Options dialog box appears with the options for formatting that you set in the preceding section.
2. In the Client Tag list, click Lowercase to reset the formatting for client tags.
3. Click OK to close the Options dialog box.
4. From the HTML group in the Toolbox, drag a Table control onto the page.
The editor creates a <table> element that has three rows (<tr> elements) and three cells (<td> elements) in each row.
Each tag is on a separate line:

<table>
<tr>
<td>
</td>
</tr>

5. In a blank part of the window, right-click, and then click Formatting and Validation.
6. Click Tag specific options.
7. Expand Default Settings.
A list of tag types appears, starting with Client tag does not support contents. By selecting an item in the list, you can
set different options for client and server elements, for elements that have content (such as a table element), and for
elements that do not (such as an img element).
8. Click Client tag supports contents.
Notice that the default setting is that tags use a separate closing tag and that the tags have line breaks before, within, and
after the tag.
9. Expand Client HTML tags.
10. Click td.
You will set options to change how td tags are formatted.
11. In the Line breaks list, click None.
12. Click OK to close the Tag Specific Options dialog box, and then click OK to close the Options dialog box.
13. On the Edit menu, click Format Document.
The document is reformatted. The <td> tags in the table that you added are placed in a single line:

<table>
<tr>
<td></td><td></td><td></td>

You can work with tag-specific options for an ASP.NET server control.
To set formatting options for an ASP.NET server control
1. Switch to Design view.
2. From the Standard group in the Toolbox, drag a ListBox control onto the page.
3. Right-click the ListBox control, and then click Show Smart Tag.
4. In the ListBox Tasks dialog box, click Edit Items.
The ListItem Collection Editor dialog box appears.
5. Click Add two times to add two items.
6. Under Members, click the first ListItem, and then under ListItem properties, set Text to Item 1.
7. Under Members, click the first ListItem, and then under ListItem properties,, set Text to Item 2.
8. Click OK to close the ListItem Collection Editor dialog box.
9. Switch to Source view.
Notice that the control has been formatted in the following manner:

<asp:Listbox ID="ListBox1" runat="server">


<asp:ListItem>Item 1</asp:Listitem>
<asp:ListItem>Item 2</asp:Listitem>
</asp:Listbox>

10. In a blank part of the window, right-click, and then click Formatting and Validation.
11. Click Tag specific options.
12. In the Tag Specific Options dialog box, click ASP.NET Controls, and then click New Tag.
13. In the Tag name box, type asp:listitem.
Do not type the right and left angle brackets (< and >) as part of the tag name.
You are setting options for the asp:ListItem element that is used inside a ListBox control. You are not setting options for
the asp:ListBox element, because you want to control how the contents (children) of the asp:ListBox element are
formatted.
14. Click OK to close the New Tag dialog box.
15. In the Line breaks list, click None.
This will cause the control to have no line breaks in it.
16. Click OK to close the Tag Specific Options dialog box, and then click OK to close the Options dialog box.
You can now see the effect of your new formatting options.
To add an ASP.NET server control using the new formatting options
1. Switch to Design view.
2. From the Standard group in the Toolbox, drag a second ListBox control onto the page.
3. Right-click ListBox, and then click Show Smart Tag.
4. On the ListBox Tasks menu, click Edit Items.
5. For the ListBox control, create two items as you did in the preceding procedure.
6. Switch to Source view.
Notice that the <asp:ListItem> elements are all on one line. The </asp:ListBox> element appears on the next line
because tag wrapping is set to 80 characters. You can modify this value in the Options dialog box.
Although you worked with only two controls and changed only one formatting option (line breaks), you can see how to apply
options to any element that you typically work with.
Outlining Elements
In Source view, you can outline elements (collapse and expand them) so that they are out of your way when you are not
working with them. This is particularly useful for elements such as tables, which often take up a lot of space. You can also use
the collapse feature for any elements in the page.
To outline elements
1. Switch to Source view.
2. Select one of the tables that you added earlier.
If you no longer have the tables, from the HTML group in the Toolbox, drag one onto the page.
3. On the Edit menu, point to Outlining, and then click Hide Selection.
The <table> tag is collapsed and a plus sign (+) is displayed in the margin.
4. Click the plus sign to expand the table element.
You can also configure elements so that the plus (+) and minus (-) signs appear automatically in the margin when the
elements exceed a certain size.
To configure how elements are outlined automatically
1. Right-click the page, click Formatting and Validation, click Format, and then click Tag specific options.
2. In the Tab Specific Options dialog box, expand Client HTML tags, and then click table.
3. Under Outlining in code editor, in the Minimum lines box, enter 5.
4. Click OK, and then click OK.
For existing tables and any new tables that are added, outlining appears automatically, if the table exceeds five lines.
Validating HTML
The HTML editor can validate your HTML or make sure that it complies with the rules for specific browsers or standards, such
as XHTML. For example, the editor can find tags and attributes that are not accepted by Netscape Navigator 4.0 or that do not
comply with XHTML standards.
In this part of the walkthrough, you will work with different schemas (browser types or standards) and introduce various types
of small errors to see how the editor flags the errors.
To test validation in the editor
1. In Source view, open or switch to the Default.aspx page.
2. On the HTML Source Editing toolbar, in the list, click Internet Explorer 3.02/Netscape Navigator 3.0.
3. Scroll to the bottom of the page.
4. Inside the </form> tag, type the following HTML:

<font face=arial>
<a href=Default.aspx >Default Page </a>
</font>

As you type, Microsoft IntelliSense technology provides assistance in completing the tags.
5. On the HTML Source Editing toolbar, in the list, click XHTML 1.0 Transitional (Netscape 7, Opera 7, Internet Explorer
6).
After a short pause (because validation is performed as a background task), you see red squiggly lines underneath
various parts of the tags. Like a spell checker, the HTML validation feature finds markup in your page that is not
acceptable for the currently selected browser.
6. In the <font> tag, rest the mouse pointer over the word font.
A ToolTip informs you that the font element is considered outdated. Current standards now recommend that you use
cascading style sheet styles for text formatting. For example, <span style="font-name:Arial;">.
7. In the href attribute of the <a> tag, rest the mouse pointer over Default.aspx.
A ToolTip informs you that in the current schema, attributes must be enclosed in quotation marks.
8. Enclose Default.aspx in quotation marks.
The value for the href attribute is no longer underlined. If you use relative references for anchor tags or other tags that
require a URL, validation determines whether the target element is available.
9. In the line below the HTML you are working with, type a right angle bracket (<).
The IntelliSense drop-down list appears, but this time it does not offer font, because the font element is not valid in
XHTML schemas.
10. Delete the right angle bracket (<).
Setting Validation Options
You can control the types of errors that validation shows you. This is useful if you want validation to find certain types of
errors, even if the errors would be allowed in a particular schema.
To set validation options
1. Right-click anywhere in the page, and then click Formatting and Validation.
Note
The Formatting and Validation command is available only in Source view.

2. In the Options dialog box, click Validation.


Notice that regardless of whether you select or clear the Show errors check box, the error display for check boxes is not
enabled. This is because the current schema is XHTML, which already shows you all possible validation errors.
3. In the Target list, click Internet Explorer 6.
4. Make sure that the Show errors check box is selected, and then under Show errors, select all check boxes.
5. Click OK to return to the editor.
6. Select the HTML that you entered in the preceding procedure, and then on the Edit menu, click Make Uppercase.
After a brief pause, the tag names are underlined. When you rest the mouse pointer over a tag name, a ToolTip indicates
that the name contains uppercase letters. Generally, Internet Explorer 6 allows for uppercase tag names, but you now see
this validation error because you have changed the validation options for that schema.
Validation can find many other types of errors also, such as duplicated control IDs, crossed opening and closing tags (for
example, <b><i></b></i>), and so on. However, validation in the editor does not prevent you from creating any HTML code
that you want. Validation just identifies markup that does not comply with the rules for the specified browser.
You should understand that when an ASP.NET page runs, the resulting output consists not only of the HTML elements that you
create, but also of the HTML that is rendered by ASP.NET server controls and any code that writes to the page. Validation
cannot examine the output of those dynamic elements; that is, the editor cannot examine the validity of generated output. By
default, ASP.NET controls generate output that complies with XHTML 1.1 standards. This means that the output is suited for
most browsers. For more information about the markup that is generated by ASP.NET controls, see ASP.NET and XHTML.
Next Steps
This walkthrough has introduced you to some of the more advanced features of the HTML editor. Although the walkthrough
did not illustrate every feature, you have seen how formatting options, outlining, and validation can help you produce well-
formed, custom-formatted markup, although still giving you final control over the markup.
See Also
Concepts
XHTML in Visual Web Developer
Markup Validation in Visual Web Developer
Other Resources
Editing Text, Code, and Markup
Product Support and Accessibility
Visual Web Developer

Walkthrough: Code Editing in Web Pages in Visual Web


Developer
Many ASP.NET Web pages involve writing code in Visual Basic, C#, or another language. The code editor in the Microsoft Visual
Web Developer Web site development tool can help you write code quickly while helping you avoid errors. In addition, the
editor provides ways for you to create reusable code to help reduce the amount of work you need to do.
This walkthrough illustrates various features of the code editor. Some of the features of the code editor depend on what
language you are coding in. Therefore, in this walkthrough you will create two pages, one that uses Visual Basic as its
programming language and another that uses C#.
During this walkthrough, you will learn how to:
Correct errors (in Visual Basic).
Refactor and rename code (in C#).
Rename symbols.
Insert code snippets (in Visual Basic and C#).
Prerequisites
In order to complete this walkthrough, you will need:
A general understanding of working in Visual Web Developer.
For an introduction to Visual Web Developer, see Walkthrough: Creating a Basic Web Page in Visual Web Developer.
Creating the Web Site and Page
If you have already created a Web site in Visual Web Developer (for example, by following the steps in
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and skip to the next section.
Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, point to New, and then click Web Site.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, select File System, and then enter the name of the folder where you want to keep the pages of your
Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click Visual Basic.
Note
Visual Web Developer currently does not support creating code-behind pages in the Microsoft Visual J# development t
ool.

The programming language you choose will be the default for your Web site, but you can set the programming language
for each page individually.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Correcting Errors in Visual Basic
The code editor in Visual Web Developer helps you to avoid errors as you code, and if you have made an error, the code editor
helps you to correct the error. In this part of the walkthrough, you will write a few lines of code that illustrate the error
correction features in the editor.
The behavior of the code editor depends on which language you are coding in. In general, the code editor for Microsoft Visual
Basic 2005 provides more detailed error information as you code.
To test error correction in Visual Basic
1. In Design view, double-click the blank page to create a handler for the Load event for the page.
You are using the event handler only as a place to write some code.
2. Inside the handler, type the following line that contains an error:

dim var1 as inger

When you press ENTER, the code editor underlines the word inger, indicating that the word is not recognized. Note that
part of the underline is a small underscore.
3. Hold the mouse pointer over the word inger to see a ToolTip that tells you what the error is.
4. Hold the mouse pointer over the underscore in the underline.
The underscore expands into an icon.
5. Click the icon.
A list of possible corrections for the word inger is displayed.
6. Select Change 'inger' to Integer.
Refactoring and Renaming in C#
Refactoring is a software methodology that involves restructuring your code to make it easier to understand and to maintain,
while preserving its functionality. A simple example might be that you write code in an event handler to get data from a
database. As you develop your page, you discover that you need to access the data from several different handlers. Therefore,
you refactor the page's code by creating a data-access function in the page and inserting calls to the function in the handlers.
The code editor includes tools to help you perform various refactoring tasks. In this walkthrough, you will work with two
refactoring techniques: renaming symbols and extracting a method. Other refactoring options include encapsulating fields,
promoting local variables to method parameters, and managing method parameters. The availability of these refactoring
options depends upon the location in the code. For example, if you highlight code that is not a field declaration, you can not
select the Encapsulate Field option. If you highlight a variable in an event method, you can not select Promote Local
Variable to Parameter because event handler signatures are constant.
Refactoring Code
A common refactoring scenario is to create (extract) a method from code that is inside another member. This reduces the size
of the original member and makes the extracted code reusable.
In this part of the walkthrough, you will write some simple code, and then extract a method from it. Refactoring is supported
for C#, so you will create a page that uses C# as its programming language.
To create a C# page
1. In Solution Explorer, right-click the name of your Web site, and then click Add New Item.
2. Under Visual Studio installed templates, click Web Form.
3. In the Language list, click C#.
Note
You can leave the name Default2.aspx.

4. Click Add to create and open the new page.

To extract a method in a C# page


1. Switch to Design view.
2. In the Toolbox, from the Standard group, drag a Button control onto the page.
3. Double-click the Button control to create a handler for its Click event, and then add the following highlighted code.
C#
protected void Button1_Click(object sender, EventArgs e)
{
System.Collections.ArrayList alist =
new System.Collections.ArrayList();
int i;
string arrayValue;
for(i=0; i<5; i++)
{
arrayValue = "i = " + i.ToString();
alist.Add(arrayValue);
}
for(i=0; i<alist.Count; i++)
{
Response.Write("<br>" + alist[i]);
}
}

The code creates an ArrayList object, uses a loop to load it with values, and then uses another loop to display the contents
of the ArrayList object.
4. Press CTRL+F5 to run the page, and then click the Button control to be sure that you see the following output:

i = 0
i = 1
i = 2
i = 3
i = 4

5. Return to the code editor, and then select the following lines in the event handler.
C#

for(i=0; i<alist.Count; i++)


{
Response.Write("<br>" + alist[i]);
}

6. Right-click the selection, click Refactor, and then choose Extract Method.
The Extract Method dialog box appears.
7. In the New Method Name box, type DisplayArray, and then click OK.
The code editor creates a new method named DisplayArray, and puts a call to the new method in the Click handler
where the loop was originally.
C#
protected void Button1_Click(object sender, EventArgs e)
{
System.Collections.ArrayList alist =
new System.Collections.ArrayList();
int i;
string arrayValue;
for(i=0; i<5; i++)
{
arrayValue = "i = " + i.ToString();
alist.Add(arrayValue);
}
i = DisplayArray(alist, i);
}

8. Press CTRL+F5 to run the page again, and click the Button control.
The page functions the same as it did before.
Renaming Symbols
When working with variables and objects (both are also known as symbols), you might want to be able to rename the symbols
after they are already referenced in your code. However, renaming the symbol can potentially cause the code to break if you
miss renaming one of the references to the symbol. Therefore, you can use refactoring to perform the renaming.
To use refactoring to rename symbols
1. In the Click event handler, locate the following line:
C#
System.Collections.ArrayList alist =
new System.Collections.ArrayList;

2. Right-click the variable name alist, choose Refactor, and choose Rename.
The Rename dialog box appears.
3. In the New name box, type ArrayList1, and then press ENTER.
The Preview Changes dialog box appears, and displays a tree containing all references to the symbol that you are
renaming.
4. Click Apply to close the Preview Changes dialog box.
The variables that refer specifically to the instance that you selected are renamed. Note, however, that the variable alist
in the following line is not renamed.
C#
private int DisplayArray(System.Collections.ArrayList alist,
int i)

The variable alist in this line is not renamed because it does not represent the same value as the specific variable alist
that you renamed. The variable alist in the DisplayArray declaration is a local variable for that method. This illustrates
that using refactoring to rename symbols is different than simply performing a find-and-replace action in the editor;
refactoring renames symbols with knowledge of the semantics of the symbol that it is working with.
Inserting Snippets
Because there are many coding tasks that Web page developers frequently need to perform, the code editor provides a library
of snippets, or blocks of prewritten code. You can insert these snippets into your page.
Each Visual Studio language has slight differences in the way you insert code snippets. For information on inserting snippets in
Visual Basic, see How to: Insert Snippets Into Your Code (Visual Basic). For information on inserting snippets in Visual J# and
Visual C#, see How to: Use Code Snippets (C#).
Next Steps
This walkthrough has illustrated the basic IntelliSense features of the Visual Studio IDE for correcting errors in your code,
refactoring code, renaming symbols, and inserting code snippets into your code. There is more to these IntelliSense features
that make application development fast and easy. For example, you might want to:
Learn more about the features of IntelliSense, such as modifying IntelliSense options, managing code snippets, and
searching for code snippets online. For more information, see Using IntelliSense.
Learn how to create your own code snippets. For more information, see Creating and Using IntelliSense Code Snippets.
Learn more about the Visual Basic-specific features of IntelliSense code snippets, such as customizing the snippets and
troubleshooting. For more information, see Visual Basic IntelliSense Code Snippets.
Learn more about the C#-specific features of IntelliSense, such as refactoring and code snippets. For more information,
see Visual C# Code Editor Features.
See Also
Concepts
Visual Basic IntelliSense Code Snippets
Refactoring
Code Snippets (C#)
Other Resources
Editing Text, Code, and Markup
Using IntelliSense
Visual Web Developer

Walkthrough: Debugging Web Pages in Visual Web Developer


Visual Web Developer provides you with tools to help track down errors in your ASP.NET Web pages. In this walkthrough, you
will work with the debugger, which allows you to step through the page's code line by line and examine the values of variables.
In the walkthrough, you will create a Web page that contains a simple calculator that squares a number. After creating the page
(which will include a deliberate error), you will use the debugger to examine the page as it is running.
Tasks illustrated in this walkthrough include:
Setting breakpoints.
Invoking debugger from a Web Forms page in a file system Web site.
Prerequisites
In order to complete this walkthrough, you will need:
Visual Web Developer and the .NET Framework.
You should also have a general understanding of working in Visual Web Developer. For an introduction to Visual Web
Developer, see Walkthrough: Creating a Basic Web Page in Visual Web Developer.
Creating the Web Site and Page
In the first part of the walkthrough, you will create a page that you can debug.
If you have already created a Web site in Visual Web Developer (for example, by working with the topic
Walkthrough: Creating a Basic Web Page in Visual Web Developer ), you can use that Web site and skip to "Adding Controls to
Debug" later in this walkthrough. Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, click File System and then type the name of the folder where you want to keep the pages of your
Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language that you prefer to work in.
The programming language you choose will be the default for your Web site. However, you can use multiple languages
in the same Web application by creating pages and components in different programming languages. For information on
creating components using different languages, see Shared Code Folders in ASP.NET Web Sites.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating a Page to Debug
You will begin by creating a new page. For this walkthrough, it is important that you create a new page as specified in the
following procedure.
To add a page to the Web site
1. Close the Default.aspx page.
2. In Solution Explorer, right-click the name of your Web site (for example, C:\WebSite) and choose Add New Item.
3. Under Visual Studio installed templates, choose Web Form.
4. In the Name box, type DebugPage.aspx.
5. From the Language list, choose the programming language you prefer to use.
6. Be sure that the Place code in separate file check box is cleared.
In this walkthrough, you are creating a single-file page with the code and HTML in the same page. The code for ASP.NET
pages can be located either in the page or in a separate class file. To learn more about keeping the code in a separate file,
see Walkthrough: Creating a Basic Web Page with Code Separation in Visual Web Developer .
7. Click Add.
Visual Web Developer creates the new page and opens it in Source view.
You can now add some controls to the page and then add code. The code will be simple, but enough to allow you to add
breakpoints later.
To add controls and code for debugging
1. Switch to Design view, and then from the Standard folder of the Toolbox, drag the following controls onto the page
and set their properties as indicated:
Control Properties
Label ID: CaptionLabel
Text: (empty)

TextBox ID: NumberTextBox


Text: (empty)

Button ID: SquareButton


Text: Square

Label ID: ResultLabel


Text: (empty)
Note
For this walkthrough, the layout of the page is not important.

2. Double-click the Button control to create a Click handler for it.


3. Add logic to the Click handler to call a function called Square to square the number entered by the user. The handler
might look like the following example.
Note
The code example deliberately does not include error checking.

VB
Sub SquareButton_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Dim number As Integer
Dim result As Integer
number = CInt(NumberTextBox.Text)
result = Square(number)
ResultLabel.Text = CStr(number) & " squared is " & CStr(result)
End Sub

C#
protected void SquareButton_Click(object sender, System.EventArgs e)
{
int number, result;
number = System.Convert.ToInt32(NumberTextBox.Text);
result = Square(number);
ResultLabel.Text = NumberTextBox.Text +
" squared is " + result.ToString();
}

4. Create the function that squares the number. Include a bug in the code to add the number to itself instead of multiplying
it. The code might look like the following example.
VB
Function Square(number As Integer) As Integer
Square = number + number
End Function

C#
int Square(int number )
{
int Square;
Square = number + number;
return Square;
}

You can also add code to the page that will change the text of the label depending on whether this is the first time the page is
running.
To change the caption Label control
1. In Design view, double-click the design surface (not a control) to create a Page_Load event handler.
2. Set the text of the Caption Label control to Enter a number: if this is the first time the page is running, or Enter
another number: otherwise. The handler will look like the following code example.
VB
Sub Page_Load(ByVal sender As Object, ByVal e as System.EventArgs)
If Page.IsPostBack = False Then
CaptionLabel.Text = "Enter a number: "
Else
CaptionLabel.Text = "Enter another number: "
End If
End Sub

C#
if(Page.IsPostBack == false)
{
CaptionLabel.Text = "Enter a number: ";
}
else {
CaptionLabel.Text = "Enter another number: " ;
}

Testing the Page


To make sure the page is working, run it in its current state.
To run the page
1. Save the page.
2. Press CTRL+F5 to run the page.
3. Enter a number (other than 2) and press the Square button.
Note that the result is incorrect, because there is a bug in the program.
4. Close the browser.
Debugging the Page
In this part of the walkthrough, you will use the debugger to examine the page code line by line as it is running, add
breakpoints to the code, and then run the page in Debug mode.
You will start by setting breakpoints in your code. A breakpoint is a line in your code where execution stops and the debugger
is invoked.
To set breakpoints
1. Switch to Source view.
2. Right-click the following line, choose Breakpoint, and then choose Insert Breakpoint.
Note
You can toggle breakpoints by pressing F9.

VB
If Page.IsPostBack = False Then

C#
if(Page.IsPostBack == false)

3. Set another breakpoint on the following line of the SquareButton_Click handler:


VB
result = Square(number)

C#
result = Square(number);

Note
You cannot set a breakpoint on a statement that declares a variable.

With at least one breakpoint set, you are ready to run the debugger.
To run the debugger
1. From the Debug menu, choose Start Debugging (or press F5) to run the page in debug mode.
If you have never run the debugger before, your application probably is not configured to support debugging. By default,
debugging is turned off in applications both for performance (pages run more slowly in the debugger) and for security
reasons. Visual Web Developer displays a message telling you what it must do to enabled debugging.
The switch to enable debugging is stored as a setting in the Web.config file, which maintains various site-specific
configuration options. If the Web.config file does not exist, Visual Web Developer will both create the file and make the
appropriate debugger setting.
If the Web.config file already exists but debugging is not enabled, you will see a slightly different message telling you that
Visual Web Developer will modify the Web.config file.
2. If you see the message telling you that debugging has not been enabled, click OK to enable debugging.
In Visual Web Developer, the designer changes to debug mode displaying the code for your page and some debugger
windows.
The debugger runs your page line by line. When the debugger gets to the line with the breakpoint, it stops and highlights
the line.
Because the breakpoint is in the Page_Load handler, the page has not finished processing yet. The browser is open, but
the page is not yet displayed.
3. In the Debug menu, click Windows, click Watch, and then click Watch 1.
Note
If you are using Visual Web Developer Express Edition, the debugger offers only a single Watch window.

This opens a Watch window, where you can specify the values you want to track.
4. In the editor, right-click the IsPostBack portion of the Page.IsPostBack expression, and then click Add Watch.
This adds the expression to the Watch window and displays the current value of the property (false) is displayed in the
Value column. If you prefer, you can type the name of a variable or property in the Name column of the Watch window.
5. From the Debug menu, choose Continue to continue execution, or press F5.
The Continue command tells the debugger to proceed until it gets to the next breakpoint. The Page_Load event handler
finishes processing and the page is displayed in the browser.
6. Enter the value 2 into the text box and click the Square button.
The debugger is displayed again, with the breakpoint on the line in the Page_Load handler. This time, the Watch
window shows you that the value of Page.IsPostBack is true.
7. Press F5 again to continue.
The debugger processes the Page_Load handler and enters the SquareButton_Click handler, where it stops on the
second breakpoint you set.
8. In the Debug menu, click Windows and then click Locals.
This opens the Locals window, which displays the values of all variables and objects that are in scope at the current line
being executed. The Locals window provides an alternative way for you to view these values, with the advantage that
you do not have to explicitly set a watch on the elements, but with the disadvantage that the window might contain more
information than you want to see at once.
In the Locals window, you see that the value of number is 2 and the value of result is 0.
Note
You can also see the value of any variable in the program by holding the mouse pointer over it.

9. In the Value column of the Locals window, right-click the line for the number variable and select Edit value. Edit the
value of the number variable and change it to 5.
The value 2 for the variable number is not a good test of the program, because adding and squaring 2 both result in 4.
Therefore, while the program is running, you can change the value of this variable.
10. From the Debug menu, choose Step Into to step into the Square function, or press F11.
The Step Into command causes the debugger to execute a line and then stop again.
11. Continue stepping by pressing F11 until you reach the following line of code.
VB
ResultLabel.Text = CStr(number) & " squared is " & CStr(result)

C#
ResultLabel.Text = NumberTextBox.Text +
" squared is " + result.ToString();

The debugger walks through your code line by line. When the debugger executes the Square function, you can use the
Locals window to check the data passed to the function (number) and the return value of the function (Square).
12. In the Debug menu, click Windows and then Immediate.
The Immediate window allows you to execute commands. You can use the window to evaluate expressions (for
example, to get the value of a property).
13. In the Immediate window, type the following expression and press Enter.

? NumberTextBox.Text

The question mark (?) is an operator in the Immediate window that evaluates the expression following it. In this
example, you are evaluating the Text property of the NumberTextBox control on the page. You can evaluate any variable,
object property, or expression that combine these, using the same syntax that you would use in code.
14. In the Immediate window, type the following and press Enter:

NumberTextBox.Text = "5"

In addition to evaluating expressions, the Immediate window allows you to change variables or properties
15. Press F5 to continue running the program.
When the page appears, it displays the result of passing 5 to the Square function. In addition, the text in the text box has
been changed to 5.
The result you see — 10 — is not correct, since 10 is not the square of 5. You can now fix the bug.
To fix the bug and test again
1. Switch from the browser to Visual Web Developer.
Note
Do not close the browser window.

2. In the Square function, change the "+" operator to the "*" operator.
Because the code is not currently running (the page has finished processing), you are in edit mode and can make
permanent changes.
3. Press CTRL+S to save the page.
4. From the Debug menu, choose Delete All Breakpoints so that the page will not stop each time you run it.
Note
You can also clear breakpoints by pressing CTRL+SHIFT+F9.

5. Switch to the browser window.


6. Enter 5 in the text box and click the button.
This time, when you run the page and enter a value, it is squared correctly. The temporary changes you made earlier,
such as changing the Text property of the NumberTextBox control, have not been persisted, because they applied only
when the page was running the last time.
7. Close the browser to stop the debugger.
Next Steps
The debugger includes additional features to help you work with your code. In addition, you might want to learn about
techniques for handling error conditions and ways in which you can monitor page processing at run time. For example, you
might want to explore tracing. For details, see
Walkthrough: Using Tracing in Visual Web Developer to Help Find Web Page Errors.
See Also
Other Resources
Debugging in Visual Studio
Visual Web Developer

Walkthrough: Creating a Local IIS Web Site in Visual Web


Developer
In the Microsoft Visual Web Developer Web development tool, you can create and edit Web sites that keep the Web pages and
other files in different locations. Your choices for locating Web pages and other files include the following:
In a folder on the local hard disk, which is referred to as a file system Web site.
As a Web application under a local copy of Microsoft Internet Information Services (IIS), which is referred as a local IIS
Web site.
You can also work with Web sites on a remote server by creating a Microsoft SharePoint Services Web site or by connecting to
a server that uses FTP. For more information, see Types of Web Sites in Visual Web Developer.
In this walkthrough, you will work with two Web sites that run under a locally installed copy of IIS. One of the Web sites is
physically located under the root folder of IIS (typically C:\Inetpub\wwwroot). A second Web site is located in a convenient
folder on the hard disk but the second Web site is available to IIS by using a virtual directory.
You can use IIS to test the Web site. If the computer is configured to permit other users to connect to it, the Web site is
available to those users.
Note
If you cannot run IIS on the computer, you can still create and test ASP.NET Web sites by running Visual Web Developer. For
more information, see Walkthrough: Creating a Basic Web Page in Visual Web Developer.

Tasks illustrated in this walkthrough include the following:


Creating an application and page under the IIS root.
Creating an application that uses an IIS virtual root.
Using IIS to run the page.
Working with IIS in Solution Explorer.
Prerequisites
To complete this walkthrough, you must have IIS installed locally on the computer, and you must be logged in as a user with
administrative privileges. This is required because working with the IIS metabase (where information about IIS applications is
stored) requires administrative privileges.
Creating a Web Site under the IIS Root
In the first part of the walkthrough, you will create a Web site that resides under the IIS default folder (typically
\Inetpub\wwwroot).
To create a new local IIS Web site under the IIS root
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. Click Browse.
The Choose Location dialog box appears.
5. Click Local IIS.
6. Click Default Web Site.
7. Click the Create new Web program icon, which is located in the upper-right corner.
This icon is not labeled, but when you pause the mouse pointer on it, the Create New Web Application ToolTip text
appears.
A new application, named WebSite, is added under Default Web Site.
8. In the box for the new Web site, type LocalIISWebSite, and then click Open.
The New Web Site dialog box appears with the right-most Location box filled in with
http://localhost/LocalIISWebSite.
9. In the Language list, click the programming language that you prefer to work in.
The programming language that you choose will be the default for the Web site. However, you can use multiple
languages in the same Web application by creating pages and components in different programming languages.
10. Click OK.
Visual Web Developer creates the new Web site and opens a new page named Default.aspx. Keep this page open. This
initial Default.aspx page uses the Web page code-behind model. For more information, see
ASP.NET Web Page Code Model.
Visual Web Developer not only creates the folders and files for the Web site but it also interacts with IIS to create an IIS Web
application for your site. Essentially, Visual Web Developer calls IIS to create the metadata that IIS requires in order to be able
to recognize your folder and pages as a Web site.
You can examine what Visual Web Developer has performed by looking at the files and folders that have been created.
To examine the structure of the local IIS Web site
1. In Microsoft Windows, click Start, and then click Run.
In the Run dialog box, in the Open box, enter C:\Inetpub\wwwroot, and then click OK.
Note
If IIS is installed on a different drive or folder, change the path, as appropriate.

Under \wwwroot, you now see a new folder named LocalIISWebSite.


2. In the Path dialog box, double-click LocalIISWebSite.
You see the contents of the Web site, which include the following:
An App_Data folder, which is created automatically by Visual Web Developer.
A Default.aspx page.
The code-behind file, which is Default.aspx.cs or Default.aspx.vb, depending on the default language for the Web
application.
You can add pages to the Web site as you would ordinarily. However, you can also add pages to the Web site externally and
Visual Web Developer will recognize them as part of the application, although you might have to update Solution Explorer in
order to see them.
Adding and Programming Controls
In this part of the walkthrough, you will add a Button, TextBox, and Label control to the page and write code to handle the
Click event for the Button control.
To add controls to the page
1. In Visual Web Developer, open or switch to the Default.aspx page, and then switch to Design view.
2. Press SHIFT+ENTER several times to make some room.
3. From the Standard group in the Toolbox, drag three controls onto the page: a TextBox, Button, and Label.
Note
If you cannot see the Toolbox, on the View menu, click Toolbox.

4. Position the insertion pointer in front of the text box, and then type Enter your name:.
5. Click the Button control, and then in Properties, set Text to Display Name.
6. Click the Label control, and then in Properties, clear Text.
7. Double-click the Button control, which is now labeled Display Name.
Visual Web Developer opens the code file for the page in a separate window in the editor.
The file contains a skeleton Click handler for the Button control.
8. Complete the Click handler by adding the following highlighted code that will display the text string after the Button
control is clicked.
Security Note
User input in an ASP.NET Web page can include potentially malicious client script. By default, ASP.NET pages check pag
es on postback to guarantee that user input does not include script or HTML elements. For more information, see
Script Exploits Overview.

VB
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handl
es Button1.Click
Label1.Text = Textbox1.Text & ", welcome to Visual Web Developer!"
End Sub

C#
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = TextBox1.Text + ", welcome to Visual Web Developer!";
}

9. Save the files.


You will test this Web page in "Testing the IIS Web Application," later in this walkthrough.
Updating the Web Site Outside Visual Web Developer
You can see that Visual Web Developer is reading the IIS path by adding a new file to the application from outside Visual Web
Developer.
To update the Web outside Visual Web Developer
1. Using Notepad or another text editor, create a new file that contains the following text, depending on whether you are
using Visual Basic or C#.
VB
<%@Page language="VB"%>
<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handl
es Button1.Click
Button1.Text = "I was clicked!"
End Sub
</script>
<html>
<body>
<form runat="server" id="form1">
<asp:button runat="server" text="Button1" Id="Button1"
OnClick="Button1_Click"></asp:button>
</form>
</BODY>
</HTML>

C#
<%@Page language="C#"%>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
Button1.Text = "I was clicked!";
}
</script>
<html>
<body>
<form runat="server" id="form1">
<asp:button runat="server" text="Button1" Id="Button1"
OnClick="Button1_Click"></asp:button>
</form>
</BODY>
</HTML>

2. Save the file in the path C:\inetpub\wwwroot\LocalIISWebSite under the name TestPage.aspx.
Note
If IIS is installed on a different drive or folder, change the path, as appropriate.

3. In Visual Web Developer, in Solution Explorer, click the Web site name (http://localhost/LocalIISWebSite/), and then
on the View menu, click Refresh.
The list of files that are in the Web site is updated to include the file that you added. Next, you will test the Web pages.
Testing the IIS Web Application
You can now test the Web site.
To test the local IIS Web site
1. In Visual Web Developer, open the Default.aspx page.
2. Press CTRL+F5 to run the page.
The page opens in the browser. Notice that the URL in the browser is http://localhost/LocalIISWebSite/default.aspx.
The request for the page is being made to localhost (without a port number), which is handled by IIS.
3. When the page appears in the browser, in the text box, enter your name, and then click Display Name to make sure it is
working.
4. In Visual Web Developer, open the TestPage.aspx page.
5. Press CTRL+F5 to run the page.
The page opens in the same instance of the browser.
6. When the page appears in the browser, click Button1 to make sure it is working.
7. Close the browser.
If you can connect to the computer from another computer, you can try accessing your site as if it were a public site. If you
cannot connect to the computer from another computer, you can skip this procedure.
To test your site as a public site
From a different computer, type the URL that includes the Web server computer name, Web site name, and default.aspx
as the page:
If the computer can be accessed over a local area network, use the computer name for the server that has a URL
such as the following:
http://server1/LocalIISWebSite/default.aspx
If you host a domain on the computer, you can access the page using a URL such as the following:
http://www.contoso.com/LocalIISWebSite/default.aspx
If the computer is either on a network or directly connected to the Internet, you can use the IP address for the
computer as the server name. For example:
http://172.19.195.700/LocalIISWebSite/default.aspx
Note
If you are not able to view your application from a different computer because of the Windows Firewall settings, you m
ight have to enable the Web server on port 80. You can do this on the Advanced tab of Windows firewall by clicking S
ettings. For more information, go to Security Developer Center -- .NET Framework Security and search for information
about Windows firewall settings.

Creating a Web Site as an IIS Virtual Root


As you have seen up to this point, IIS lets you create Web applications that are physically located under the default Web server
root folder (wwwroot). However, you can also create IIS virtual directories, which are IIS Web applications that point to files and
folders that can be located anywhere on the hard disk.
Note
For security reasons, IIS does not let you create virtual directories that point to folders on other computers. Virtual directories
must always point to the local computer.

In this part of the walkthrough, you will use Visual Web Developer to create a virtual directory that points to a Web site that is
stored in a local folder on the computer.
The first step is to create the virtual directory. If you have already created a file system Web site in Visual Web Developer (for
example, by completing Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site.
To create a local IIS Web site using a virtual folder
1. In Visual Web Developer, on the File menu, click New Web site.
2. Under Visual Studio Installed Templates, click ASP.NET Web Site.
3. Click Browse.
The Choose Location dialog box appears.
4. Click Local IIS.
5. Under Select the Web site you want to open, in the tree view, click Default Web Site, and then click the Create new
virtual directory icon, which is located in the upper-right corner.
This icon is not labeled, but when you pause the mouse pointer on it, the Create New Virtual Directory ToolTip text
appears.
The New Virtual Directory dialog box appears.
6. In the Alias Name box, type WebSite_vdir.
Note
You can name your virtual directory anything that you like, as long as you use a name that is valid in IIS.
7. In the Folder box, type one of the following:
The path of an existing file system Web site, if you have one. You can click Browse, and then locate the root folder
of that site, if you do not remember the exact path.
The path where you want to create a new folder to store the folders and files for the Web site.
8. Click OK.
If you specified a folder that does not exist, Visual Web Developer prompts you to create it.
Visual Web Developer then returns to the Choose Location dialog box and updates the list of IIS Web applications that
have the virtual directory that you created.
9. Select the virtual directory that you just created, click Open, and then click OK to create the Web site.
If you pointed the virtual directory to a new folder or an existing folder that does not contain a Web site, Visual Web
Developer creates the App_Data folder, a default page, and opens the page in the designer.
If your virtual folder points to an existing file system Web site, Visual Web Developer opens a Web Site Already Exists
dialog box and gives you the option to select a new folder, open the existing site, or create a new Web site in the existing
location. After you select your option and click OK, Visual Web Developer displays the contents of the folder in Solution
Explorer and opens the Default.aspx page, if it exists.
Adding Controls to the Web Page
As you did in " Testing the IIS Web Application," earlier in this walkthrough, you will use a simple ASP.NET Web page to test the
IIS Web site that you are creating. If you are working with an existing file system Web site, you do not have to create a new
page. If your virtual directory points to a new folder, you can use that page.
If this is a new Web site, you will add some controls to the default page so that you can test that the page is working correctly.
To add controls to the page
1. In Visual Web Developer, open the Default.aspx page and switch to Design view.
2. From the Standard group in the Toolbox, drag a TextBox, Button, and Label control onto the page.
3. Double-click the Button control, and then add the following highlighted code:
VB
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handl
es Button1.Click
Label1.Text = "Welcome to Visual Web Developer!"
End Sub

C#
protected void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text = "Welcome to Visual Web Developer!";
}

4. Save the files.


Testing the Virtual Directory
You can now test the Web site.
To test the local IIS Web site using the virtual directory
1. In Visual Web Developer, open a page in the Web site, which can be the Default.aspx page or another page.
2. Press CTRL+F5 to run the page.
The page opens in the browser. Notice that the URL in the browser is http://localhost/Website_vdir/default.aspx.
When IIS resolves the URL, it looks up the physical path that is associated with the virtual directory named Website_vdir
and looks for the page there.
3. When the page appears in the browser, click the Button control to make sure it is working.
4. Close the browser.
If you can connect to the computer from another computer, you can try the same tests that you used in the preceding section
to try accessing the page.
Deleting a Local IIS Web Site
You can manage local IIS Web sites in Visual Web Developer by deleting ones that you no longer need. There is an important
difference in how deletion works, depending on which type of local IIS Web site that you are working with, as follows:
When you delete a Web site under the IIS root, the Web application is deleted from IIS and the files and folders for the
Web site are deleted also.
When you delete a virtual directory, the IIS information about that Web site is deleted but the files and folders in the local
file system folder are left intact.

To delete the local IIS Web site


1. On the File menu, click Close Solution or Close Project.
2. On the File menu, click Open Web site.
3. In the Open Web Site dialog box, click Local IIS.
4. Click the name of the virtual directory (Website_vdir) that you created in "Creating a Web Site as an IIS Virtual Root,"
earlier in the walkthrough.
Caution
If you select a different Web site, the files and folders for that Web site might be deleted.

5. Click the delete icon in the upper-right corner.


This icon is not labeled, but when you pause the mouse pointer on it, the Delete ToolTip text appears.
6. When you are prompted for confirmation to delete the Web site, click Yes.
7. Click Cancel to close the Open Web Site dialog box.
8. Open the browser, and then type the URL for the virtual directory:
http://localhost/Website_vdir/default.aspx
This time, the browser reports that the page cannot be found, because IIS no longer recognizes Website_vdir as a Web
site on the local computer.
Note
It is possible that the page was cached by the local browser. In that case, the page might still display until you flush the
browser cache, and then try to view the page again.

Next Steps
In this walkthrough, you have learned how to create a Web site using the local copy of IIS. You might also want to learn about
other types of Web sites that you can create in Visual Web Developer. For example, you might want to do the following:
Create a file system Web site, where the pages are stored in a folder anywhere on the hard disk.
For more information, see Walkthrough: Creating a Basic Web Page in Visual Web Developer.
Learn how to use FTP to open and edit Web sites.
For more information, see Walkthrough: Editing Web Sites with FTP in Visual Web Developer.
See Also
Concepts
Types of Web Sites in Visual Web Developer
Using Visual Web Developer as a Non-Administrative User
Visual Web Developer

Walkthrough: Editing Web Sites with FTP in Visual Web


Developer
The Microsoft Visual Web Developer Web development tool lets you read from and write to a remote server by using the File
Transfer Protocol (FTP). The most common use for FTP Web sites is to update Web pages on a hosting site, which is faster than
updating files that use an HTTP connection. After you connect to the FTP site in Visual Web Developer, you can create and edit
files in those sites. For information about FTP, see FTP-Deployed Web Sites.
Tasks illustrated in this walkthrough include the following:
Using FTP to connect to an existing Web site from within Visual Web Developer.
Creating and editing pages by using FTP.
Prerequisites
In order to complete this walkthrough, you will need the following:
Access to a folder on an FTP server that supports the .NET Framework.
If you have access to an existing FTP site, you can use that. For example, if you have an account that has a commercial
hosting service that provides ASP.NET support, you can use that account in this walkthrough. Otherwise, you can
configure a computer by running Microsoft Internet Information Services (IIS) as an FTP server. For more information
about how to configure IIS as an FTP server, see How to: Create and Configure FTP Sites in IIS.
Read and write permissions for the FTP directory on the server.
Optionally, a virtual Web root that points to the FTP location. This lets you to test the files that you work with.
For purposes of this walkthrough, you can use a local copy of IIS as an FTP server. Ordinarily, you do not have to use FTP to
communicate with the local copy of IIS.
Accessing the FTP Web Site
To start, you will connect to the FTP Web site from within Visual Web Developer. You must know the FTP address of the FTP
Web site and, if it is required, you must have a user name and password.
To access the FTP Web site
1. In Visual Web Developer, on the File menu, click New Web Site.
2. In the New Web Site dialog box, in the left-most Location list, click FTP Site, and then click Browse.
3. In the Choose Location dialog box, in the Server and Directory boxes, enter the appropriate information.
The Server field refers to the name or IP address of the FTP server. The Directory field refers to a specific directory on
the FTP server that you want to put the content in. By default, many FTP sites connect you to a home directory, although
there might still be a directory below that or a separate virtual directory where the Web content should be put. If you do
not know these values, contact the FTP site administrator.
For Port, the most common value is 21, but you should confirm that value with the FTP site administrator also.
4. Examine the following values:
Passive Mode
Leave this check box clear at first. Passive mode is sometimes required, if there is a firewall between your server
and the FTP server.
Anonymous Login
If the FTP site administrator has provided you with a user name and password, clear the Anonymous Login check
box, and then in the Username and Password boxes, enter the appropriate information.
5. Click Open.
Visual Web Developer will try to connect to the FTP server by using the information that you have provided. If the
connection is successful, Visual Web Developer displays the FTP Web site name in Solution Explorer and lists the files
that are already in the FTP Web site.
Troubleshooting
If the connection fails, examine the following:
If you have administrative rights on the server, use IIS Manager to add the Write permission to the FTP virtual directory.
Do not complete this before you have set restricted NTFS File System permissions on the virtual directory, either by
using IIS Manager or Microsoft Windows Explorer. For more information, go to Microsoft Technet and search for
information about how to help secure FTP sites.
Confirm that the server name and directory name are correct.
Use the URL of the Web site or the FTP site in the Server field and leave the Directory field blank.
Try connecting with Passive Mode enabled. This frequently lets you get through a firewall.
Make sure that the FTP Web site has the directory that you have indicated. If you are using IIS as the FTP server,
remember that the directory is typically defined under the ftproot directory, not the wwwroot directory.
Contact the FTP site administrator to determine whether anonymous log on is allowed. If not, make sure that you have
credentials for a user account that has permission to access and modify the FTP directory.
Creating and Editing Pages
Working with Web pages in an FTP Web site is the same as working with Web pages in any other Web site. The only difference
is that the files are stored on the FTP server, so that when you open or save the files, you are invoking the FTP connection.
To create a page
1. In Solution Explorer, right-click the FTP Web site name, click Add New Item, and then create a new Web Forms page.
Note
If you have access to the physical folder that is represented by the FTP Web site, you can confirm that the file is created
in that folder.

2. Switch to Design view.


3. From the Standard group in the Toolbox, drag a Button control and a Label control onto the page.
4. Double-click the Button control.
5. The file contains a skeleton Click handler for the Button control.
6. Complete the Click handler by adding the following highlighted code:
VB
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Label1.Text = "The FTP Web site is working!"
End Sub

C#
protected void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text = "The FTP Web site is working!";
}

7. Save your files.


Testing the FTP Web Site
If the FTP Web site has been set up to have an equivalent Web site, you can test the Web site by displaying it in the browser.
To test the FTP Web site on the server
1. Press CTRL+F5.
Visual Web Developer prompts you for the location to go to. The location is stored as part of the Web site configuration
information.
2. Enter the HTTP URL that points to the server and the Web virtual directory that you created in "Accessing the FTP Web
Site," earlier in this walkthrough.
For example, the URL might be the following:
http://<server>/ExampleFtpFiles

Note
You can change or set the browser location at any time. To do this, in Solution Explorer, right-click the Web site name, a
nd then click Property Pages. On the Start Options tab, under Server, click Use custom server, and then in the Base
URL box, type the location.

The page is displayed in the browser.


3. Close the browser.
See Also
Concepts
What's New in Web Development for Visual Studio
Types of Web Sites in Visual Web Developer
Visual Web Developer

Walkthrough: Using Shared Code in Web Sites in Visual Web


Developer
When you are creating Web sites, Visual Web Developer lets you easily create shared code in class files, which can then be
used by pages in your application, even without compiling the class files.
Note
If you have existing assemblies (.dll files), you can add them to the Bin directory of the Web site, and then the assemblies are
automatically referenced by the Web site.

In this walkthrough, you will create a simple class and then use it in an ASP.NET Web page.
Tasks illustrated in this walkthrough include the following:
Adding a class to a Web site.
Having Visual Web Developer reference the component automatically.
Prerequisites
In order to complete this walkthrough, you will need the following:
Visual Web Developer (Visual Studio).
The .NET Framework.
This walkthrough assumes that you have a general understanding of working in Visual Web Developer. For an introduction,
see Walkthrough: Creating a Basic Web Page in Visual Web Developer.
Creating the Web Site and Page
If you have already created a Web site in Visual Web Developer (for example, by completing either
Walkthrough: Creating a Basic Web Page in Visual Web Developer or
Walkthrough: Creating a Local IIS Web Site in Visual Web Developer), you can use that Web site and go to the next section.
Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site. (In Visual Web Developer Express Edition, on the File menu, click New, and then
click Web Site.)
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of the Web site.
For example:
If you are creating a file system Web site, type C:\SampleSite.
If you have IIS installed and you are creating an HTTP Web site, type http://localhost/SampleSite.
5. In the Language list, select the programming language that you prefer to work in.
6. Click OK.
Visual Web Developer creates the Web site and opens a new page named Default.aspx.
Creating a Shared Class
You can create reusable classes by keeping them in a folder named App_Code. Visual Web Developer monitors the App_Code
folder and when new class files are added, makes the components available to the rest of the code in your application. By
default, the classes in the App_Code folder are compiled into a single assembly at run time.
Note
You should put only classes (and other supported shared types) into the App_Code folder. Do not put pages, Web user contr
ols, or other files that contain non-code elements into the App_Code folder.

To create an App_Code folder


In Solution Explorer, right-click the name of the Web site, click Add Folder, and then click App_Code Folder.
You can now add the component to your site.
To create a shared class in the App_Code folder
1. In Solution Explorer, right-click App_Code, and then click Add New Item.
Note
Be sure to create the new item in the App_Code folder, not in the root folder of the Web site.

2. Under Visual Studio installed templates, click Class.


3. In the Name box, type SampleClass1.
4. In the Language list, select the language that is used by the Web page that will use the shared class.
5. Click Add.
Visual Web Developer opens the new class file in the editor.
6. Create a class that has a single property named testString by copying the following code into the class file:
VB
Public Class SampleClass1
private testStringValue As String
Public Property testString as String
Get
return testStringValue
End Get
Set (Value as String)
testStringValue = value
End Set
End Property
End Class

C#
using System;
public class SampleClass1
{
public SampleClass1()
{
}
private string testStringValue;
public string testString
{
get
{
return testStringValue;
}
set
{
testStringValue = value;
}
}
}

7. Save the file and then close it.


Note that the file is not stored as a compiled file.
Note
When you work with shared classes in the App_Code folder, you do not have to save the components in order for Visu
al Web Developer to maintain a reference to the components. If the Web page and component are in the same progra
mming language, Visual Web Developer maintains a reference to the component in memory. In this case, you are closi
ng the file because you are finished with it.

Using the Shared Class


The next step is to use the shared class in an ASP.NET Web page. You can use the Default.aspx page that was created when you
created the Web site.
To use the shared class
1. Open or switch to the Default.aspx page, and then switch to Design view.
Note
If you do not have a Default.aspx page, you can use another page. Alternatively, you can add a new page to the Web sit
e. To do this, in Solution Explorer, right-click the name of the Web site, click Add New Item, and then click Web Form.
In the Language list, enter the same programming language that you used for the component, and then click OK.

2. From the Standard folder in the Toolbox, drag a TextBox control, Label control, and Button control onto the page.
Note
For this walkthrough, the layout of the page is not important.

3. Double-click the Button control to create a Click handler for it.


The click handler code might look similar to the following:
VB
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click

End Sub

C#
protected void Button1_Click(object sender, EventArgs e)
{

4. In the handler, type the following:


VB
Dim sc As New
C#
SampleClass1 sc = new

When you press SPACEBAR after typing New or new, Visual Web Developer displays a list of the available classes. The
class that you created in the preceding section, SampleClass1, is included in the list.
5. Finish the statement by typing SampleClass1 or by double-clicking it in the list, so that the statement reads as follows:
VB
Dim sc As New SampleClass1

C#
SampleClass1 sc = new SampleClass1();

6. Press ENTER, and then type the following:

sc.

As soon as you type the period, Visual Web Developer again displays a list of members to help you select a member
from the sample class.
7. Finish the statement and the handler in the following manner:
VB
sc.testString = TextBox1.Text
Label1.Text = sc.testString

C#
sc.testString = TextBox1.Text;
Label1.Text = sc.testString;

8. Save your files.


Testing the Page and Class
You can run the Web site to see that the shared class is working.
To test the page and component
1. Open the Default.aspx page.
2. Press CTRL+F5 to run the page.
3. When the page appears in the browser, type something in the text box, and then click the button.
Doing this sets a property in your simple class, which is then displayed in the Label control.
If you use Microsoft Windows Explorer to examine the directory where the Web site is located, you will see your page and the
App_Code folder. Note that there is no .dll or other executable code in the App_Code folder or anywhere under the root of the
Web site. Instead, Visual Web Developer has compiled the page and the shared class dynamically.
Next Steps
This walkthrough illustrates how to add shared classes to a Web site without compiling the components. You might want to
use shared classes in different ways. For example, you might want to:
Work with a compiled component.
If you have an assembly that you can use in the Web site, create a Bin folder, and then copy the .dll to Bin. You can then
reference the assembly in your page in the same way that you referenced the component that you created in this
walkthrough.
Create a component for data access.
For more information, see Walkthrough: Data Binding to a Custom Business Object.
Create a Web service.
For more information, see Walkthrough: Creating and Using an ASP.NET Web Service in Visual Web Developer.
See Also
Concepts
ASP.NET Web Site Layout
Shared Code Folders in ASP.NET Web Sites
Visual Web Developer

Data-Driven Web Pages


The topics in this section include step-by-step walkthroughs that illustrate various ways to display and edit data using ASP.NET
Web pages and how to optimize data access using caching.
In This Section
Walkthrough: Basic Data Access in Web Pages
Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control
Walkthrough: Displaying and Formatting Data with the DataList Web Server Control
Walkthrough: Displaying Formatted Data in Web Pages with the FormView Web Server Control
Walkthrough: Creating Master/Detail Web Pages in Visual Studio
Walkthrough: Data Binding Web Pages with a Visual Studio Data Component
Walkthrough: Data Binding to a Custom Business Object
Walkthrough: Creating a Web Page to Display XML Data
Walkthrough: Displaying Hierarchical Data in a TreeView Control
Walkthrough: Using Output Caching to Enhance Web Site Performance
Walkthrough: Using ASP.NET Output Caching with SQL Server
Related Sections
Guided Tour of Creating Web Sites in Visual Web Developer
Introduces topics designed to give a guided tour of creating Web sites in Microsoft Visual Web Developer.
Visual Web Developer

Walkthrough: Basic Data Access in Web Pages


This walkthrough shows you how to create a simple data-bound page by using controls that are specially designed for data
access.
During this walkthrough, you will learn how to do the following:
Connect to a Microsoft SQL Server database in the Microsoft Visual Web Developer Web development tool.
Use drag-and-drop editing to create data-access elements that can be used in the page without code.
Use the SqlDataSource control to manage data access and binding.
Display data with the GridView control.
Configure the GridView control to allow for sorting and paging.
Create a filtered query that displays only selected records.
Prerequisites
In order to complete this walkthrough, you will need the following:
Access to the SQL Server Northwind database. For information about downloading and installing the SQL Server sample
Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site.
Note
If you need information about how to log on to the computer running SQL Server, contact the server administrator.

Microsoft Data Access Components (MDAC) version 2.7 or later.


If you are using Microsoft Windows XP or Windows Server 2003, you already have MDAC 2.7. However, if you using
Microsoft Windows 2000, you might have to upgrade the MDAC version that is already installed on the computer. To
download the current MDAC version, see Data Access and Storage Developer Center.
Creating the Web Site
If you have already created a Web site in Visual Web Developer by completing
Walkthrough: Creating a Basic Web Page in Visual Web Developer, you can use that Web site and go to the next section.
Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the right-most Location box, enter the name of the folder where you want to keep the pages of the Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language that you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Adding a GridView Control to Display Data
To display data on an ASP.NET Web page, you need the following:
A connection to a data source (such as a database).
In the following procedure, you will create a connection to the SQL Server Northwind database.
A data source control on the page, which executes queries and manages the results of the queries.
A control on the page to actually display the data.
In the following procedure, you will display data in a GridView control. The GridView control will get its data from the
SqlDataSource control.
You can add these elements to the Web site separately. However, it is easiest to start by visualizing the data display using
GridView control, and then using wizards to create the connection and data source control. The following procedure explains
how to create all three of the elements that you must have to display data on the page.
To add and configure a GridView control for displaying data
1. In Visual Web Developer, switch to Design view.
2. From the Data folder in the Toolbox, drag a GridView control onto the page.
3. If the GridView Tasks shortcut menu does not appear, right-click the GridView control, and then click Show Smart Tag.
4. On the GridView Tasks menu, in the Choose Data Source list, click <New data source>.
The Data Source Configuration dialog box appears.

5. Click Database.
This specifies that you want to obtain data from a database that supports SQL statements. This includes SQL Server and
other OLE-DB–compatible databases.
In the Specify an ID for the data source box, a default data source control name appears (SqlDataSource1). You can
leave this name.
6. Click OK.
The Configure Data Source Wizard appears, displaying a page on which you can choose a connection.
7. Click New Connection.
8. In the Choose Data Source dialog box, under Data source, click Microsoft SQL Server, and then click Continue.
The Add Connection dialog box appears.
9. In the Server name box, enter the name of the SQL Server that you want to use.

10. For the logon credentials, select the option that is appropriate for accessing the SQL Server database (integrated security
or specific ID and password) and if it is required, enter a user name and password.
11. Click Select or enter a database name, and then enter Northwind.
12. Click Test connection, and when you are sure that it works, click OK.
The Configure Data Source - <DataSourceName> Wizard appears and the connection information is filled in.
13. Click Next.
The wizard appears, displaying a page on which you can choose to store the connection string in the configuration file.
Storing the connection string in the configuration file has two advantages:
a. It is more secure than storing the connection string in the page.
b. You can reuse the same connection string in multiple pages.
14. Make sure that the Yes, save this connection as check box is selected, and then click Next. (You can leave the default
connection string name of NorthwindConnectionString.)
The wizard appears, displaying a page on which you can specify the data that you want to fetch from the database.
15. Under Specify columns from a table or view, in the Name list, click Customers.
16. Under Columns, select the CustomerID, CompanyName, and City check boxes.
The wizard appears, displaying the SQL statement that you are creating in a box at the bottom of the page.

Note
The wizard lets you specify selection criteria (a WHERE clause) and other SQL query options. For this part of the walkthr
ough, you will create a simple statement without selection or sort options.

17. Click Next.


18. Click Test Query to make sure that you are fetching the data you want.
19. Click Finish.
The wizard closes and you are returned to the page. Running the wizard has accomplished two tasks:
The wizard created and configured a SqlDataSource control (named SqlDataSource1), which incorporates the
connection and query information that you specified.
The wizard bound the GridView control to the SqlDataSource. Therefore, the GridView control will display data
that is returned by the SqlDataSource control.
If you view the properties for the SqlDataSource control, you can see that the wizard has created values for the
ConnectionString and SelectQuery properties.
Note
You can easily change the look of the GridView control. In Design view, right-click the GridView control, and then clic
k Show Smart Tag. On the GridView Tasks menu, click Auto Format, and then apply a scheme.
Testing the Page
You can now run the page.
To test the page
1. Press CTRL+F5 to run the page.
The page appears in the browser. The GridView control displays all data rows from the Customers table.
2. Close the browser.
Adding Sorting and Paging
You can add sorting and paging to the GridView control without writing any code.
To add sorting and paging
1. In Design view, right-click the GridView control, and then click Show Smart Tag.
2. On the GridView Tasks shortcut menu, select the Enable Sorting check box.
The column headings in the GridView control change to links.
3. On the GridView Tasks menu, select the Enable Paging check box.
A footer is added to the GridView control with page number links.
4. Optionally, use Properties to change the value of the PageSize property from 10 to a smaller page size.
5. Press CTRL+F5 to run the page.
You will be able to click a column heading to sort by the contents of that column. If there are more records in the data
source than the page size of the GridView control, you will be able to use the page navigation links at the bottom of the
GridView control to move between pages.
6. Close the browser.
Adding Filtering
Frequently you want to display only selected data in the page. In this part of the walkthrough, you will modify the query for the
SqlDataSource control so that users can select customer records for a particular city.
First, you will use a TextBox control to create a text box in which users can type the name of a city. Then, you will change the
query to include a parameterized filter (WHERE clause). As part of that process, you will create a parameter element for the
SqlDataSource control. The parameter element establishes how the SqlDataSource control will get the value for its
parameterized query—namely, from the text box.
When you are finished with this part of the walkthrough, the page might look similar to the following in Design view.
To add the text box for specifying a city
1. From the Standard group in the Toolbox, drag a TextBox control and a Button control onto the page.
The Button control is used only to post the page to the server. You will not need to write any code for it.
2. In Properties, for the TextBox control, set ID to textCity.
3. If you want, type City or similar text before the text box to act as a caption.
4. In Properties for the Button control, set Text to Submit.
You can now modify the query to include a filter.
To modify the query with a parameterized filter
1. Right-click the SqlDataSource control, and then click Show Smart Tag.
2. On the SqlDataSource Tasks menu, click Configure Data Source.
The Configure Data Source - <Datasourcename> wizard appears.
3. Click Next.
The wizard displays the SQL command that is currently configured for the SqlDataSource control.
4. Click WHERE.
The Add WHERE Clause page appears.
5. In the Column list, click City.
6. In the Operator list, click =.
7. In the Source list, click Control.
8. Under Parameter properties, in the Control ID list, click textCity.

The previous five steps specify that the query will get the search value for City from the TextBox control that you added
in the preceding procedure.
9. Click Add.
The WHERE clause that you have created appears in a box at the bottom of the page.
10. Click OK to close the Add WHERE Clause page.
11. In the Configure Data Source - <DataSourceName> wizard, click Next.
12. On the Test Query page, click Test Query.
The wizard appears, displaying the Parameter Values Editor page, which prompts you for a value to use in the WHERE
clause.
13. In the Value box, type London, and then click OK.
The customer records for London appear.
14. Click Finish to close the wizard.
You can now test filtering.
To test filtering
1. Press CTRL+F5 to run the page.
2. In the text box, type London, and then click Submit.
A list of customers from the city of London appears in the GridView control.
3. Try other cities, such as Buenos Aires and Berlin.
Next Steps
Data access is an important part of many Web applications, and this walkthrough has provided only a glimpse of what you can
do with data in the Web pages. You might want to experiment with additional features of data access. For example, you might
want to do the following:
Work with Microsoft Access instead of SQL Server. (You cannot use SQL cache dependency with Access.)
For detailed information, see Walkthrough: Creating a Web Page to Display Access Database Data.
Edit and insert records.
For detailed information, see
Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control.
Work with records that have a master-detail relationship.
For detailed information, see Walkthrough: Creating Master/Detail Web Pages in Visual Studio.
Create a middle-tier (business) component that performs data access, and then use that as the data source in a page.
For detailed information, see Walkthrough: Data Binding to a Custom Business Object.
See Also
Concepts
Data Source Controls Overview
Visual Web Developer

Walkthrough: Editing and Inserting Data in Web Pages with


the DetailsView Web Server Control
Microsoft Visual Web Developer allows you to create data entry forms for updating records and inserting new ones into a
database with only a few lines of code. By using a combination of a data source control that encapsulates data access and
DetailsView and GridView controls that display records in an editable format, you can create a data entry page that allows
users to edit existing records or insert new ones, all without any code.
During this walkthrough, you will learn how to:
Create a data entry page.
Configure a data source control with information required to make database updates and inserts.
Use the DetailsView control to view individual records, change them, and insert new ones.
Use a GridView control to enable database modification from the data entry page.
Prerequisites
In order to complete this walkthrough, you will need:
Visual Web Developer.
Microsoft Data Access Components (MDAC) version 2.7 or later.
If you are using the Microsoft Windows XP or Windows Server 2003 operating systems, you already have MDAC 2.7.
However, if you are using the Microsoft Windows 2000 Server operating system, you might need to upgrade the MDAC
already installed on your computer. To download the current MDAC version, see the
Data Access and Storage Developer Center.
Access to the SQL Server Northwind database. For information about downloading and installing the SQL Server sample
Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site.
Note
If you need information about how to log on to the computer running SQL Server, contact the server administrator.

Permission to modify data in the sample Northwind database.


Creating the Web Site and Page
Create a new Web site and page by following these steps.
To create a new file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New, and then click Web Site. If you are using Visual Web Developer Express, on the File menu,
click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, select File System, and enter the name of the folder where you want to keep the pages of your Web
site.
For example, type the folder name C:\WebSites\EditData.
5. In the Language list, click the programming language you prefer to work in.
The programming language you choose will be the default for your Web site, but you can set the programming
languages for each page individually.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Connecting to SQL Server
The next step is to establish a connection to the SQL Server database.
To create a connection to a SQL Server database
1. In Server Explorer, right-click Data Connections, and then click Add Connection. If you are using Visual Web
Developer Express, use Database Explorer.
The Add Connection dialog box appears.
If the Data source list does not display Microsoft SQL Server (SqlClient), click Change, and in the Change Data
Source dialog box, select Microsoft SQL Server.
If the Choose Data Source page appears, in the Data source list, select the type of data source you will use. For
this walkthrough, the data source type is Microsoft SQL Server. In the Data provider list, click .NET Framework
Data Provider for SQL Server, and the click Continue.
Note
If the Server Explorer tab is not visible in Visual Web Developer, in the View menu, click Server Explorer. If the Data
base Explorer tab is not visible in the Express edition, in the View menu, click Database Explorer.

2. In the Add Connection box, enter your server name in the Server Name box.
3. For the Log on to the server section, select the option that is appropriate to access the running the SQL Server database
(integrated security or specific ID and password) and, if required, enter a user name and password. Select the Save my
Password check box if you entered a password.
4. Under Select or enter a database name, enter Northwind.
5. Click Test Connection, and when you are sure that it works, click OK.
Your new connection has been created under Data Connections in Server Explorer.
Creating the Data Entry Page
In this section, you will create a data entry page and configure a DetailsView control so that you can view employee data that
is stored in the Employees table of the Northwind database. To handle the data access for the page, you will configure a SQL
data source control.
To create a data entry page and configure a DetailsView control
1. On the Website menu, click Add New Item.
The Add New Item dialog box appears.
2. Under Visual Studio installed templates, click Web Form, and then in the Name box, type EditEmployees.aspx.
3. Click Add.
4. Open the EditEmployees.aspx page.
5. Switch to Design view.
6. Type Edit Employees, select the text, and then format the text as a heading.
7. In the Toolbox, from the Data group, drag a DetailsView control onto the page.
8. Right-click the DetailsView control, click Properties, and then set AllowPaging to true.
This will allow you to page through individual employee entries when they are displayed.
The next step is to create and configure a data source control that can be used to query the database. There are a number of
ways to create a data source control, including dragging data elements from Server Explorer or Database Explorer onto the
page. In this walkthrough, you will start with the DetailsView control and configure the data source control from there.
To configure a data source control
1. Right-click the DetailsView control and click Show Smart Tag.
2. On the DetailsView Tasks menu, in the Choose Data Source box, click <New data source>.
The Data Source Configuration Wizard dialog box appears.
3. Under Select a data source type, click Database.
4. Leave the default name of SqlDataSource1, and then click OK.
The Configure Data Source wizard displays the Choose a connection page.
5. In the Which data connection should your application use to connect to the database? box, enter the connection
that you created in "To create a connection to SQL Server," and then click Next.
The wizard displays a page where you can choose to store the connection string in a configuration file. Storing the
connection string in the configuration file has two advantages:
It is more secure than storing it in the page.
You can use the same connection string in multiple pages.
6. Select the Yes, save this connection as check box, and then click Next.
The wizard displays a page where you can specify what data you want to retrieve from the database.
7. On the Configure the Select Statement page, select Specify columns from a table or view, and then in the Name
box, click Employees.
8. Under Columns, select the EmployeeID, LastName, FirstName, and HireDate check boxes, and then click Next.
9. Click Test Query to preview the data, and then click Finish.
You can now test the employee records display page.
To test displaying the employee records
1. Press CTRL+F5 to run the page.
The first employee record is displayed in the DetailsView control.
2. Click the page number links to see additional employee records.
3. Close the browser.
Allowing Editing in a GridView Control
At this point, you can view employee records, but you cannot edit them. In this section, you will add a GridView control and
configure it so that you can edit individual records.
Note
The GridView control presents a list of records and allows you to edit them. However, it does not allow you to insert them. L
ater in this walkthrough, you will use the DetailsView control, which allows you to add new records.

To support editing, you must configure the data source control you created earlier (SqlDataSource1) with SQL statements that
perform updates.
To add a GridView control to allow editing
1. In the Toolbox, from the Data group, drag a GridView control onto the page.
2. Right-click the GridView control, click Show Smart Tag, and then on the GridView Tasks menu, in the Choose Data
Source box, click SqlDataSource1.
3. On the GridView Tasks menu, click Configure Data Source.
4. Click Next to advance to the Configure the Select Statement page of the wizard.
5. On the Configure the Select Statement page, click Advanced, select the Generate INSERT, UPDATE, and DELETE
statements check box, and then click OK.
This generates Insert, Update, and Delete statements for the SqlDataSource1 control based on the Select statement that
you configured earlier.
Note
Alternatively, you could manually create the statements by selecting Specify a custom SQL statement or stored pro
cedure and entering SQL queries.

6. Click Next, and then click Finish.


The SqlDataSource control is now configured with additional SQL statements.
Note
You can examine the statements generated by the wizard by selecting the SqlDataSource control and viewing the
DeleteQuery, InsertQuery, and UpdateQuery properties. You can also view the updated control properties by switching
to Source view and examining the markup of the control.

7. On the GridView Tasks menu, select the Enable Paging and Enable Editing check boxes.
Security Note
User input in an ASP.NET Web page can include potentially malicious client script. By default, ASP.NET Web pages valid
ate user input to make sure input does not include script or HTML elements. As long as this validation is enabled, you d
o not need to explicitly check for script or HTML elements in user input. For more information, see
Script Exploits Overview.

You can now test the editing of employee records.


To test the editing in the GridView control
1. Press CTRL+F5 to run the page.
The GridView control is displayed with the data in text boxes.
2. Choose a row in the GridView control and click Edit.
3. Make a change to the record, and then click Update.
The updated data now appears in both the GridView control and the DetailsView control.
4. Close the browser.
Allowing Editing, Deleting, and Inserting Using a DetailsView Control
The GridView control allows you to edit records, but it does not allow you to insert data. In this section, you will modify the
DetailsView control so that you can see records individually, as well as delete, insert, and update records.
To use a DetailsView control to allow deleting, inserting, and updating
1. Right-click the DetailsView control and then click Show Smart Tag.
2. On the DetailsView Tasks menu, select the Enable Inserting, Enable Editing, and Enable Deleting check boxes.
When you used the DetailsView control earlier in the walkthrough, the options for enabling editing, inserting, and
deleting were not available. The reason is that the SqlDataSource1 control that the DetailsView control is bound to did
not have the necessary SQL statements. Now that you have configured the data source control to include update
statements, the update options are available on the DetailsView control.
You can now test deleting, inserting, and updating in the DetailsView control.
To test the updating, inserting, and deleting in the DetailsView control
1. Press CTRL+F5 to run the page.
The DetailsView control displays an employee record.
2. In the DetailsView control, click Edit.
The DetailsView control now displays the data in text boxes.
3. Make a change to the record, and then click Update.
The updated record is displayed in the control.
4. In the DetailsView control, click New.
The control now displays blank text boxes for each column.
5. Enter values for each column.
The Employees table has an auto-increment key column, so the value for EmployeeID is assigned automatically when
you save the record.
6. When you are finished, click Insert.
The new record is added as the last record.
Note
Inserting a new record in the Employees table in this walkthrough will not generate any errors. However, when you wo
rk with production data, the tables might have constraints (such as a foreign key constraint) that you must be aware of
when configuring the DetailsView control.

7. Use paging in the DetailsView control to navigate to the last record, and then click Delete.
The new record is removed.
Note
As with inserting data, you must always be aware of any constraints that apply to the data row when configuring a Det
ailsView control to allow deletion.

Next Steps
This walkthrough has illustrated the basics of creating a Web page that allows users to modify data records. You might want to
explore additional data capabilities of ASP.NET Web pages. For example, you might want to do the following:
Work with records in related tables. For details, see Walkthrough: Creating Master/Detail Web Pages in Visual Studio.
Use a middle-tier component for data access. For details, see Walkthrough: Data Binding to a Custom Business Object.
Use other ways to configure data access in a Web page. For details, see Walkthrough: Basic Data Access in Web Pages.
See Also
Tasks
Walkthrough: Creating a Web Page to Display Access Database Data
Concepts
Data Source Controls Overview
Binding to Data Using a Data Source Control
Visual Web Developer

Walkthrough: Displaying and Formatting Data with the


DataList Web Server Control
A common task in Web pages is to display data — in effect, to create data reports. In this walkthrough, you will work with the
DataList control, which allows you to create free-form layout for records that you display on an ASP.NET Web page.
During this walkthrough you will learn how to:
Add a DataList control and use templates to lay out the data that is displayed by the DataList control.
Bind the DataList control to a data source.
Add a child data control and some code to the DataList control to display data in a master/detail relationship.
Prerequisites
In order to complete this walkthrough, you will need:
Microsoft Visual Web Developer (Visual Studio).
Access to the SQL Server Northwind database. For information about downloading and installing the SQL Server sample
Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site.
Note
If you need information about how to log on to the computer running SQL Server, contact the server administrator.

Microsoft Data Access Components (MDAC) version 2.7 or later.


If you are using Microsoft Windows XP or Windows Server 2003, you already have MDAC 2.7. However, if you are using
Microsoft Windows 2000, you might need to upgrade the MDAC already installed on your computer. For more
information, see "Microsoft Data Access Components (MDAC) Installation" in the MSDN Library.
Creating the Web Site
Create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New, and then click Web Site. If you are using Visual Web Developer Express, on the File menu,
click New Web Site.
The New Web Site dialog box is displayed.
3. Under Visual Studio installed templates, select ASP.NET Web Site.
4. In the Location box, select File System, and enter the name of the folder where you want to keep the pages of your Web
site.
For example, type the folder name C:\WebSites\FormatDataList.
5. In the Language list, click the programming language you prefer to work in.
The programming language you choose will be the default for your Web site, but you can set the programming language
for each page individually.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Adding a DataList Control
For the first part of this walkthrough, you will add a DataList control, and then configure its data source.
To add and configure a DataList control to display data in a grid
1. Switch to Design view.
2. In the Toolbox, from the Data group, drag a DataList control onto the page.
3. Right-click the DataList control, and then click Show Smart Tag.
4. On the DataList Tasks menu, in the Choose Data Source list, click New Data Source.
The Configure Data Source wizard appears.
5. Click Database.
This specifies that you want to get data from a database that supports SQL statements. (This includes SQL Server and
other OLE-DB–compatible databases.)
6. In the Specify an ID for the data source box, a default data source control name is displayed (SqlDataSource1). You
can leave this name.
7. Click OK.
The Configure Data Source wizard displays a page in which you can create a connection.
8. Click New Connection.
If the Choose Data Source page appears, in the Data source list, select the type of data source you will use. For
this walkthrough, the data source type is Microsoft SQL Server. In the Data provider list, click .NET Framework
Data Provider for SQL Server, and the click Continue.
The Add Connection page appears.
9. On the Add Connection page, in the Server name text box, type the name of the computer running the SQL Server
database.
10. For the logon credentials, select the option that is appropriate for accessing the computer running the SQL Server
database (either integrated security or a specific ID and password) and, if required, enter a user name and password.
11. Select the Save my Password check box.
12. Click the Select or enter a database name button, and then enter Northwind.
13. Click Test Connection, and when you are sure that it works, click OK.
The Configure Data Source wizard appears with the connection information filled in.
14. Click Next.
The Configure Data Source wizard displays a page in which you can choose to store the connection string in the
configuration file. Storing the connection string in the configuration file has two advantages:
It is more secure than storing it in the page.
You can reuse the same connection string in multiple pages.
15. Be sure that the Yes, save this connection as check box is selected, and then click Next. You can leave the default
connection string.
The Configure Data Source wizard displays a page in which you can specify what data you want to fetch from the
database.
16. Make sure that Specify columns from a table or view is selected.
17. In the Name list, click Categories.
18. Under Columns, select the CategoryID and CategoryName check boxes.
The Configure Data Source wizard displays the SQL statement that you are creating in a box at the bottom of the page.
Note
The Configure Data Source wizard allows you to specify selection criteria (a WHERE clause) and other SQL query opti
ons. For this part of the walkthrough, you will create a simple statement with no selection or sort options.

19. Click Next.


20. Click Test Query to be sure that you are getting the data you want.
21. Click Finish.
The Configure Data Source wizard closes and you are returned to the SqlDataSource control. If you view the
properties for the SqlDataSource control, you can see that the Configure Data Source wizard has created values for
the ConnectionString and SelectQuery properties. Even though Properties in Visual Web Developer displays the full
connection string, only the connection string identifier is saved in the page (in this case, NorthwindConnectionString).
Formatting the Layout of the DataList Control
At this point, you have a DataList control on the page with a default layout for information from the Categories table. The
benefit of the DataList control is that you can create a free-form layout for the data. In this section, you will work with a
template and configure it with text and controls to customize the data display.
To format the layout in the DataList control
1. Right-click the DataList control, click Edit Template, and then click Item Templates.
The DataList control switches to template editing mode and displays template boxes for these templates:
ItemTemplate, which contains the text and controls that are displayed by default in the DataList control.
AlternatingItemTemplate, which is an optional template in which you can create a layout that is used for every
other data record. Typically, the AlternatingItemTemplate property is similar to the ItemTemplate property, but the
AlternatingItemTemplate property uses a different background color for a banded effect.
SelectedItemTemplate, which defines the layout for a data record that is explicitly selected using a button click or
other gesture. Typical uses for this template are to provide an expanded view of a data record or to serve as the
master record for a master/detail relationship. You must write code to support putting a record into selected mode.
(You will not do so in this walkthrough. For more information, see
How to: Allow Users to Select Items in DataList Web Server Controls and
Walkthrough: Creating Master/Detail Web Pages in Visual Studio.)
EditItemTemplate, which defines the layout for edit mode for a data record. Typically, the EditItemTemplate
property includes editable controls, such as the TextBox and CheckBox controls in which users can modify the data
record. You must write code to support putting a record into edit mode and to handle saving the record when the
edits are complete. (You will not do so in this walkthrough. For information about writing code to edit records, see
How to: Allow Users to Edit Items in DataList Web Server Controls.)
By default, Visual Web Developer populates the item template with a data-bound Label control for each data column in
the data source. In addition, Visual Web Developer generates static text for each label to act as a caption.
2. Drag the right-hand resize handle to widen the DataList control so it takes up most of the page width.
3. Edit the item template to rearrange the Label controls and create a new caption so that the template contents look
similar to the following code example.

Name: [CategoryNameLabel] (ID: [CategoryIDLabel])

4. Click the CategoryNameLabel control. In Properties, expand the Font node, and then set Bold to true.
5. In Design view, on the DataList control, right-click the title bar, click Edit Template, and then click Separator Template.
The separator template allows you to specify what text or other elements are displayed between data records.
6. In the Toolbox, from the HTML group, drag a Horizontal Rule element into the separator template.
7. On the DataList control, right-click the title bar, and then click End Template Editing.
Testing the DataList Control
You can now test the layout that you have created.
To test the DataList control
Press CTRL+F5 to run the page.
The page displays a list of category names and IDs, with a line between each record.
Displaying Related Information Inside the DataList Control
The DataList control that you are using currently displays individual Category records, using the custom layout that you
defined previously. You changed the default layout only a little bit, but you can see that by working with the template, you can
arrange text and controls, format the content, and modify the data record display in other ways.
The layout can include the current record, as well as related records. In this part of the walkthrough, you will change the layout
so that each row displays a category and the products in that category. In effect, you will display a master/detail relationship
within each row of the DataList control. You will need to write a short piece of code to enable this scenario.
To display related information inside the DataList control
1. Right-click the DataList control, click Edit Templates, and then click Item Templates.
2. In the Toolbox, from the Standard group, drag a BulletedList control onto the item template, and then drop the
BulletedList control below the category information.
The BulletedList control can display data, with one data column per bulleted item.
3. Right-click the BulletedList control, and then click Show Smart Tag.
4. Click Choose Data Source.
You will create a second data source control to read the related records.
5. In the Choose Data Source dialog box, in the Select a data source list, click New Data Source.
6. Click Database.
7. In the Specify an ID for the data source box, type bulletedListDataSource.
Although you can usually leave the default name for the data source, in this case it is useful to assign a specific,
predictable name to the data source so that you can reference it later in code.
8. Click OK.
The Configure Data Source wizard appears.
9. In the Which data connection should your application use to connect to the database? list, click the name of the
connection that you created earlier in this walkthrough, and then click Next.
The Configure Data Source wizard displays a page in which you can create an SQL statement.
10. Under Specify columns from a table or view, in the Name box, click Products.
11. In the Columns box, select the ProductName box.
The BulletedList control displays only one column.
12. Click the WHERE button.
The Add WHERE Clause dialog box appears.
13. In the Column list, click CategoryID.
14. In the Operator list, click =.
15. In the Source list, click None.
This indicates that the value of the CategoryID column will be provided in a variable.
16. Click Add, click OK, click Next, and then click Finish.
Testing the query will not work with the variable.
17. In the Select a data field to display in the BulletedList list, click ProductName. Click OK.
18. In the DataList control, right-click the title bar, and then click End Template Editing.
Writing Code to Set the Category ID
The SQL statement that you created for the bulletedListDataSource control looks similar to the following code:

SELECT [ProductName] FROM [Products] WHERE ([CategoryID] = @CategoryID)

At run time, the DataList control displays a list of category records, which includes both the category name and the category
ID. In the preceding section, you added a BulletedList control that will display all the products for each category. As each
category record is being displayed, the DataList control executes a query to get the products for that category, using the
preceding query.
For each record being displayed, you must provide the category ID to the query. You can do this by writing a short piece of
code that gets the category ID from the record that is currently being displayed, and then passes the category ID as a
parameter to the query in the bulletedListDataSource control.
To write code to set the category ID
1. Click the DataList control, and then in Properties, on the toolbar, click Events.
2. Double-click ItemDataBound to create an event handler for that event.
3. Copy the following code into the handler.
VB
If e.Item.ItemType = ListItemType.Item Or _
e.Item.ItemType = ListItemType.AlternatingItem Then
Dim ds As SqlDataSource
ds = CType(e.Item.FindControl("bulletedListDataSource"), _
SqlDataSource)
Dim categoryID As String
categoryID = DataBinder.Eval(e.Item.DataItem, _
"categoryid").ToString()
ds.SelectParameters("CategoryID").DefaultValue = _
categoryID
End If

C#
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
SqlDataSource ds;
ds = e.Item.FindControl("bulletedListDataSource")
as SqlDataSource;
ds.SelectParameters["CategoryID"].DefaultValue =
DataBinder.Eval(e.Item.DataItem,
"categoryid").ToString();
}

The ItemDataBound event is raised for each data record being displayed, providing you with an opportunity to read or
modify the data. This code does the following:
a. Checks to be sure that the event is occurring while binding an ItemTemplate or AlternatingItemTemplate
object (and not a SeparatorTemplate object or other type of template).
b. Uses the FindControl method to get a reference to the SqlDataSource control instance that is created inside each
item template.
c. Gets the value of the CategoryID data column by evaluating the current DataItem property.
d. Sets the CategoryID variable of the parameterized query by setting its DefaultValue property in the
SelectParameters collection.
Testing the Code
You can now test your code.
To test the code to set the category ID
Press CTRL+F5 to run the page.
The DataList control displays each category record, and for each record, it also displays, in a bulleted list, the products
that belong to that category.
Next Steps
This walkthrough has illustrated a simple but complete scenario for displaying and formatting data with the DataList Web
server control. You can create more sophisticated data-driven pages and applications using the techniques and controls
illustrated in the walkthrough. For example, you might want to:
Write code to allow users to select items in the DataList Web server control. For more information, see
How to: Allow Users to Select Items in DataList Web Server Controls.
Create a master record for a master/detail relationship. For more information, see
Walkthrough: Creating Master/Detail Web Pages in Visual Studio.
Learn how to use output caching in your data applications to improve performance. For more information, see
Walkthrough: Using Output Caching to Enhance Web Site Performance.
See Also
Tasks
How to: Allow Users to Select Items in DataList Web Server Controls
Walkthrough: Creating Master/Detail Web Pages in Visual Studio
Reference
DataList
Concepts
Walkthrough Topics — ASP.NET Data Access (Visual Studio)
Visual Web Developer

Walkthrough: Displaying Formatted Data in Web Pages with


the FormView Web Server Control
ASP.NET provides various controls that allow you to display and edit data records. In this walkthrough, you will work with the
FormView control, which works with a single data record at a time. The FormView control's primary feature is that it allows
you to create the record layout yourself by defining templates. By working with templates, you can have complete control over
the layout and appearance of the data within the control. The FormView control also supports updates such as editing,
inserting, and deleting data records. If the data source provides more than one record to the FormView control, the control
allows you to page through the records individually.
Note
You can also edit individual data records with the DetailsView control, which provides a predefined layout for the data. For de
tails, see DetailsView Web Server Control (Visual Studio).

Tasks illustrated in this walkthrough include:


Creating a page to display master/detail information.
Using a FormView control to create a free-form layout for a data record.
Configuring the FormView control to allow editing.
Prerequisites
In order to complete this walkthrough, you will need:
Microsoft Visual Web Developer.
Access to the SQL Server Northwind database. For information about downloading and installing the SQL Server sample
Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site.
Note
If you need information about how to log on to the computer running SQL Server, contact the server administrator.

Microsoft Data Access Components (MDAC) version 2.7 or later.


If you are using Microsoft Windows XP or Windows Server 2003, you already have MDAC 2.7. However, if you are using
Microsoft Windows 2000, you might need to upgrade the MDAC already installed on your computer. For more
information, see "Microsoft Data Access Components (MDAC) Installation" in the MSDN Library.
Creating the Web Site
Create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New, and then click Web Site. If you are using Visual Web Developer Express, on the File menu,
click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of your Web site.
For example, type the folder name C:\WebSites\FormViewData.
5. In the Language list, click the programming language you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Using a Drop-Down List as the Master
In this part of the walkthrough, you will add a drop-down list to a page and populate it with a list of product names. When
users select a product, the page will display the details for that product in a FormView control.
To create and populate a drop-down list
1. Switch to or open the Default.aspx page. If you are working with a Web site you had already created, add or open a page
that you can work with in this walkthrough.
2. Switch to Design view.
3. Type Display Product Information in the page.
4. From the Standard group in the Toolbox, drag a DropDownList control onto the page.
5. If the DropDownList Tasks menu does not appear, right-click the DropDownList control, and then click Show Smart
Tag.
6. On the DropDownList Tasks menu, select the Enable AutoPostBack check box.
7. Click Choose Data Source to open the Data Source Configuration Wizard.
8. In the Select a data source list, click <New Data Source>.
9. Click Database.
This specifies that you want to get data from a database that supports SQL statements.
In the Specify an ID for the data source box, a default data source control name is displayed. You can leave this name.
10. Click OK.
The wizard displays a page where you can select a connection.
11. Click the New Connection button.
The Add Connection dialog box appears.
If the Data source list does not display Microsoft SQL Server (SqlClient), click Change, and in the Change Data
Source dialog box, select Microsoft SQL Server.
If the Choose Data Source page appears, in the Data source list, select the type of data source you will use. For
this walkthrough, the data source type is Microsoft SQL Server. In the Data provider list, click .NET Framework
Data Provider for SQL Server, and then click Continue.
12. In the Add Connection dialog box, do the following:
a. In the Server name box, enter the name of the computer running SQL Server.
b. For the logon credentials, select the option that is appropriate to access the running the SQL Server database
(integrated security or specific ID and password) and, if required, enter a user name and password. Select the Save
my Password check box if you entered a password.
c. Select the Select or enter a database name button, and then enter Northwind.
d. Click Test connection, and when you are sure that the connection works, click OK.
You are returned to the wizard, and the connection information is filled in.
13. Click Next.
14. Be sure that the Yes, save this connection as check box is selected, and then click Next. (You can leave the default
connection string name.)
The wizard displays a page where you can specify what data you want to retrieve from the database.
15. Click Specify columns from a table or view.
16. In the Name list, click Products.
17. Under Columns, select ProductID and ProductName.
18. Click Next.
19. Click Test Query to be sure that you are retrieving the data you want.
20. Click Finish.
You are returned to the wizard.
21. In the Select a data field to display in the DropDownList list, click ProductName.
22. From the Select a data field for the value of the DropDownList list, select ProductID.
This specifies that when an item is selected, the ProductID field will be returned as the value of the item.
23. Click OK.
Before proceeding, test the drop-down list.
To test the drop-down list
1. Press CTRL+F5 to run the page.
2. When the page is displayed, examine the drop-down list.
3. Select a product name to be sure that the list performs a postback.
Adding a FormView Control
You will now add a FormView control to display product details. The FormView control gets its data from a second data
source control that you add to the page. The second data source control contains a parameterized query that gets the product
record for the item currently selected in the DropDownList control.
To add a FormView control
1. From the Data group in the Toolbox, drag a FormView control onto page.
2. If the FormView Tasks menu does not appear, right-click the FormView control, and then click Show Smart Tag.
3. On the FormView Tasks menu, in the Choose Data Source list, click <New Data Source>.
The Data Source Configuration Wizard dialog box appears.
4. Click Database.
The FormView control will get data from the same table as the DropDownList control.
In the Specify an ID for the data source box, a default data source control name is displayed. You can leave this name.
5. Click OK.
The Configure Data Source wizard starts.
6. From the Which data connection should your application use to connect to the database? list, select the
connection you created and stored earlier in the walkthrough.
7. Click Next.
The wizard displays a page where you can create a SQL statement.
8. From the Name list under Specify columns from a table or view, select Products.
9. In the Columns box, select ProductID, ProductName, and UnitPrice.
10. Click the WHERE button.
The Add WHERE Clause dialog box is displayed.
11. From the Column list, select ProductID.
12. From the Operator list, select =.
13. From the Source list, select Control.
14. Under Parameter properties, in the Control ID list, select DropDownList1.
The last two steps specify that the query will get the search value for the product ID from the DropDownList control you
added earlier.
15. Click Add.
16. Click OK to close the Add WHERE Clause dialog box.
17. Click Advanced.
The Advanced SQL Generation Options dialog box appears.
18. Select the Generate INSERT, UPDATE, and DELETE statements check box.
This option causes the wizard to create SQL update statements based on the Select statement you have configured. Later
in the walkthrough you will use the FormView control to edit and insert records, which requires update statements in
the data source control.
19. Click OK.
20. Click Next.
21. In the Preview page, click Test Query.
The wizard displays a dialog box that prompts you for a value to use in the WHERE clause.
22. In the Value box, type 4 and then click OK.
The product information appears.
23. Click Finish.
Customizing the Layout in the FormView Control
The reason to use the FormView control is that you can define the layout of the record that it displays. In this section of the
walkthrough, you will customize the record layout by editing a template. For your layout, you will use an HTML table.
To format the layout
1. Click the FormView control to select it, and then drag the resize handle on the right side of the control to make the
control as wide as the current page.
2. Drag the resize handle on the bottom of the control to change the height of the control to about 400 pixels. (The exact
height is not important.)
3. Right-click the control, click Edit Template, and then click ItemTemplate.
The control is redisplayed in item template editing mode. The item template contains the static text and controls that are
used to display the data record when the page runs. By default, Visual Web Developer populates the item template with a
data-bound Label control for each data column in the data source. In addition, Visual Web Developer generates static text
for each label to act as a caption.
The template is also generated with three LinkButton controls with the text Edit, Delete, and New.
4. Put the insertion point at the top of the item template, press ENTER a few times to make room, and then at the top of the
template type Product Details to act as a heading.
5. Put the insertion point below the controls and static text and, in the Layout menu, click Insert Table.
You are creating an HTML table as a container for the text and controls.
6. In the Insert Table dialog box, do the following:
a. Set Rows to 4.
b. Set Columns to 2.
c. Click the Cell Properties button, and set Width to 35 pixels (px) and Height to 30 pixels (px).
7. Click OK to close the Cell Properties dialog box, and then click OK to close the Insert Table dialog box.
8. Drag the ProductIdLabel control into the top right-hand cell.
9. Drag the ProductNameLabel control into the second right-hand cell.
10. Drag the UnitPriceLabel control into the third right-hand cell.
11. In the left-hand column, type static text to act as captions for the Label controls. For example, in the cell next to the
ProductIdLabel control, type ID. You can type any caption text that you like.
12. Right-click the left-hand column, click Select, and then click Column.
13. In the Properties window, set align to right to make the caption text right-aligned.
14. Select the right-hand column and drag its right-hand border to make the table wide enough to display long product
names.
15. Select the text generated by Visual Web Developer (for example, the text ProductID) and delete it.
16. Right-click the FormView control's title bar and click End Template Editing.
The template editor closes and the control appears with the layout you have created.
Testing the FormView Control
You can now test your layout.
To test the FormView control
1. Press CTRL+F5 to run the page.
2. In the DropDownList control, click a product name.
The FormView control displays details about that product.
3. Select a different product and confirm that the FormView control displays the product details.
4. Close the browser.
Adding Edit and Insert Capabilities to the FormView Control
The FormView control can display individual records and also supports editing, deleting, and inserting.
In this part of the walkthrough, you will add the ability to edit the currently displayed record. To edit the record, you define a
different template that contains text boxes (and potentially other controls).
To add editing capability to the FormView control
1. Right-click the FormView control, click Edit Template, and click EditItemTemplate.
The template editor appears, displaying the EditItemTemplate property, which defines how records are laid out when the
control is in edit mode. Visual Web Developer populates the edit template with a TextBox control for each data column
that is not a key and adds static text for captions. This is similar to the way the item template was generated, except that
in the edit template, Visual Web Developer generates text boxes.
As before, the template is generated with Update and Cancel LinkButton controls that are used to save and discard
changes while editing.
2. Optionally, add a layout table and arrange the controls as you did when working with the item template earlier in the
walkthrough.
3. Right-click the FormView control, click Edit Template, and then click InsertItemTemplate.
As with the EditItemTemplate property, Visual Web Developer automatically creates a template layout of labels and
TextBox controls. The controls will be displayed when users want to insert a new record into the Products table. The
template is also generated with Insert and Cancel LinkButton controls.
4. Optionally, add a layout table and arrange the controls as you did when working with the edit item template.
5. Right-click the FormView control and click End Template Editing.
Security Note
User input in an ASP.NET Web page can include potentially malicious client script. By default, ASP.NET Web pages valid
ate user input to make sure input does not include script or HTML elements. As long as this validation is enabled, you d
o not need to explicitly check for script or HTML elements in user input. For more information, see
Script Exploits Overview.

Testing Editing and Inserting


You can now test editing and inserting.
To test editing capabilities of the FormView control
1. Press CTRL+F5 to run the page.
2. Select a product in the DropDownList control.
The product details appear in the FormView control.
3. Click Edit.
The FormView control switches to edit mode.
4. Make a change to the product name or unit price.
5. Click Update.
The record is saved and the FormView control switches to display mode. The change is reflected in the display.
6. Select a different product.
7. Click Edit.
8. Make a change to the product name.
9. Click Cancel.
Confirm that the change was not saved.

To test insert capabilities of the FormView control


1. Click New in the FormView control.
The FormView control switches to insert mode, displaying two empty text boxes.
2. Enter a new product name and price, and then click Insert.
The record is saved in the database and the FormView control switches to display (ItemTemplate) view.
Note
The new record is not displayed in the drop-down list. You will add that capability in the next section.

Redisplaying Updated Product Names in the Drop-Down List


Your page now allows you to view, edit, or delete records in the Products database table. However, the drop-down list is not
yet synchronized with changes that you make in the FormView control. For example, if you insert a new Products record, the
drop-down list does not display the new record unless you close the page and reopen it. In addition, the page is displayed
initially with the first record in the Products table, which might not be what you want.
You can add some code to fix these minor issues. In this section of the walkthrough, you will do the following:
Update the drop-down list whenever users edit or insert a record.
Add the text "(Select)" to the drop-down list when the page first appears, and remove it when the user has made the first
selection.

To update the drop-down list when records are edited or inserted


1. In Design view of the page, select the FormView control.
2. In the Properties window, click the Events button to display a list of events for the FormView control.
3. Double-click the ItemInserted box.
Visual Web Developer switches to code-editing view and creates a handler for the ItemInserted event.
4. Add the following highlighted code to the event handler.
VB
Protected Sub FormView1_ItemInserted(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.FormViewInsertedEventArgs) _
Handles FormView1.ItemInserted
DropDownList1.DataBind()
End Sub

C#
protected void FormView1_ItemInserted(object sender,
FormViewInsertedEventArgs e)
{
DropDownList1.DataBind();
}

The code runs after the new record has been inserted. It re-binds the drop-down list to the Products table, which causes
the contents of the list to be refreshed.
5. Switch to Design view. (If you are working with a code-behind page, switch to the Default.aspx page and then switch to
Design view.)
6. In the Properties window, click the Events button to display a list of events for the FormView control.
7. Double-click the ItemUpdated box.
Visual Web Developer switches to code-editing view and creates an event handler for the ItemUpdated event.
8. Add the following highlighted code.
VB
Protected Sub FormView1_ItemUpdated(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.FormViewUpdatedEventArgs) _
Handles FormView1.ItemUpdated
DropDownList1.DataBind()
End Sub

C#
protected void FormView1_ItemUpdated(object sender,
FormViewUpdatedEventArgs e)
{
DropDownList1.DataBind();
}

The code runs after the record has been updated. It re-binds the drop-down list to the Products table, which causes the
contents of the list to be refreshed.
9. Press CTRL+F5 to run the page.
10. Edit the product name of a record, click Update, and then examine the drop-down list to be sure that the updated name
is displayed.
11. Insert a new product record, click Insert, and then examine the drop-down list to be sure that the new name has been
added to the list.
The final step is to change the drop-down list to display "(Select)" and to display the FormView control only when users have
made a selection.
To add a Select entry to the DropDownList control
1. In Design view, double-click a blank part of the page.
Visual Web Developer creates an event handler for the page's Load event.
2. In the handler, add the following highlighted code.
VB
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
FormView1.Visible = False
End If
End Sub

C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FormView1.Visible = false;
}
}

The code runs when the page runs. It tests first to see if this is a postback; if not, this is the first time the page has run. If it
is not a postback, the code hides the FormView control, because you want to display it only when the user has explicitly
selected a record to view or edit.
3. In Design view for the page, select the DropDownList control.
4. In the Properties window, click the ellipsis (...) in the Items box.
The ListItem Collection Editor dialog box appears.
5. Click Add to create a new item.
6. Under ListItem properties, in the Text box, type (Select).
7. Click OK to close the ListItem Collection Editor dialog box.
8. In the Properties box, set AppendDataBoundItems to true.
When the drop-down list is populated during data binding, the product information will be added to the (Select) item
you defined.
9. In the Properties window, click the Events button to display a list of events for the DropDownList control.
10. Double-click the SelectedIndexChanged box.
11. Add the following highlighted code.
VB
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender _
As Object, ByVal e As System.EventArgs) _
Handles DropDownList1.SelectedIndexChanged
If DropDownList1.Items(0).Text = "(Select)" Then
DropDownList1.Items.RemoveAt(0)
End If
FormView1.Visible = True
End Sub
C#
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
if(DropDownList1.Items[0].Text == "(Select)")
{
DropDownList1.Items.RemoveAt(0);
}
FormView1.Visible = true;
}

The code runs when users select an item in the DropDownList control. It removes the "(Select)" item that you added
earlier (checking first to be sure it exists), because after the first time users have selected an item, you no longer need to
prompt them to select an item. The code also displays (un-hides) the FormView control so that users can see the record
they have selected.
12. Press CTRL+F5 to run the page.
The page displays only the drop-down list, with the word (Select) displayed.
13. Select an item in the list.
The item is displayed in the FormView control.
14. Examine the drop-down list and note that the word (Select) is no longer in the list.
Next Steps
This walkthrough has shown you the basic steps for using a FormView control to display and edit individual data records
using a custom layout. The FormView control allows you to perform more sophisticated formatting than what you have done
in this walkthrough. In addition, you can create templates for other modes, including selection mode and insertion mode, and
for headers and footers that are displayed with the record. For other scenarios to explore with the FormView, see the
following:
Creating Templates for the FormView Web Server Control
Modifying Data Using a FormView Web Server Control
See Also
Other Resources
FormView Web Server Control
DetailsView Web Server Control
Visual Web Developer

Walkthrough: Creating Master/Detail Web Pages in Visual


Studio
Many Web pages display data in more than one way, often displaying data from related tables. This walkthrough shows you
various ways to work with data in multiple controls and from multiple tables, including those that have a master/detail
relationship. Tasks illustrated in this walkthrough include:
Populating a drop-down list with database data.
Creating filters — SQL statements with a WHERE clause (parameterized queries).
Displaying filtered data based on the user's selection in a drop-down list.
Displaying details about a selected record using the DetailsView control.
Selecting a record in one page and displaying a related record in a second page.
Prerequisites
In order to complete this walkthrough, you will need:
Access to the SQL Server Northwind database. For information about downloading and installing the SQL Server sample
Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site.
Note
If you need information about how to log on to the computer running SQL Server, contact the server administrator.

Microsoft Data Access Components (MDAC) version 2.7 or later.


If you are using Microsoft Windows XP or Windows Server 2003, you already have MDAC 2.7. However, if you are using
Microsoft Windows 2000, you might to need to upgrade the MDAC already installed on your computer. For more
information, see the article " Microsoft Data Access Components (MDAC) Installation" in the MSDN Library.
Creating the Web Site
If you have already created a Web site in Microsoft Visual Web Developer (for example, by following the steps in
Walkthrough: Creating a Basic Web Page in Visual Web Developer or Walkthrough: Basic Data Access in Web Pages), you can
use that Web site and skip to the next section, "Connecting to SQL Server." Otherwise, create a new Web site and page by
following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of your Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Connecting to SQL Server
To work with data, you need to establish a connection to a database. In this walkthrough, you will create a connection
independently of working with Web pages or controls.
To create a connection to SQL Server
1. Press CTRL+ALT+S to display the Database Explorer. In Database Explorer, right-click Data Connections and choose
Add Connection.
The Change Data Source dialog box is displayed.
2. In the Change Data Source dialog box, select Microsoft SQL Server. and click OK.
3. In the Add Connection dialog box, do the following:
Enter or select the name of your SQL Server computer. For a server on your computer, enter (local).
Select Use SQL Server Authentication.
Enter a user name and password.
Select Save my password.
Select Northwind as the database.
4. Click Test Connection, and when you are sure that it works, click OK.
The connection is added to Server Explorer.
Using a Drop-Down List as the Master
In this part of the walkthrough, you will add a drop-down list to a page and populate it with a list of categories from the
Northwind table. When users select a category, the page will display the products for that category.
To create and populate a drop-down list
1. Switch to or open the Default.aspx page. If you are working with a Web site you had already created, add or open a page
that you can work with in this walkthrough.
2. Switch to Design view.
3. Type Select Products By Category in the page and format the text as a heading using the Block Format drop-down list
above the Toolbox.
4. From the Standard group in the Toolbox, drag a DropDownList control onto the page.
5. In the DropDownList Tasks, select the Enable AutoPostBack check box.
This configures the control so that it causes the page to post back to the server whenever a selection is made from the
list, rather than waiting until the user clicks a button.
6. In the DropDownList Tasks, select Choose Data Source.
The Choose Data Source wizard starts.
7. In the Select a data source list, click <New Data Source>.
The Data Source Configuration Wizard dialog box is displayed.
8. Select Database.
This specifies that you want to get data from a database that supports SQL statements. (This includes SQL Server and
other OLE-DB-compatible databases.)
In the Specify an ID for the data source box, a default data source control name is displayed (SqlDataSource1). You
can leave this name.
9. Click OK.
The wizard displays the Configure Data Source - SqlDataSource1 page in which you can select a data connection.
10. From the drop-down list, select the Northwind connection you created earlier in the walkthrough.
11. Click Next.
The wizard displays a page in which you can choose to store the connection string in the configuration file.
12. Be sure the Yes, save this connection as check box is selected, and then click Next. (You can leave the default
connection string name.)
The wizard displays a page in which you can specify what data you want to retrieve from the database.
13. From the Name list under Table or View Options, select Categories.
14. In the Columns box, select CategoryID and CategoryName.
15. Click Next.
16. Click Test Query to be sure that you are getting the data you want.
17. Click Finish.
The Data Source Configuration Wizard is displayed, with the name of the data source control you have configured
displayed.
18. From the Select a data field to display in the DropDownList list, select CategoryName.
Note
If no items appear in the list, click the Refresh Schema link.

This specifies that the value of the CategoryName field will be displayed as the text of the item in the drop-down list.
19. From the Select a data field for the value of the DropDownList list, select CategoryID.
This specifies that when an item is selected, the CategoryID field will be returned as the value of the item.
20. Click OK.
Before proceeding, test the drop-down list.
To test the drop-down list
1. Press CTRL+F5 to run the page.
2. When the page is displayed, examine the drop-down list.
3. Select a category to be sure that the list performs a postback.
You can now display products for the category selected in the drop-down list.
Using a Grid to Display Detail Information
You can now extend the page to include a grid. When users make a selection from the categories drop-down list, the grid will
display the products for that category.
To use a grid to display detail information
1. Switch to or open the Default.aspx page (or the page you have been working with), and switch to Design view.
2. From the Data group of the Toolbox, drag a GridView control onto the page.
3. From the GridView Tasks menu, select <New Data Source> from the Choose Data Source list.
The Data Source Configuration Wizard opens.
4. Select Database.
In the Specify an ID for the data source box, a default data source control name is displayed (SqlDataSource2). You
can leave this name.
5. Click OK.
The wizard displays a page where you can select a connection.
6. From the connections drop-down list, select the connection you created and stored earlier in the walkthrough
(NorthwindConnectionString).
7. Click Next.
The wizard displays the Configure Data Source - SqlDataSource2 page in which you can create a SQL statement.
8. From the Name list, select Products.
9. In the Columns box, select ProductID, ProductName, and CategoryID.
10. Click WHERE.
The Add WHERE Clause dialog box is displayed.
11. From the Column list, select CategoryID.
12. From the Operator list, select =.
13. From the Source list, select Control.
14. Under Parameter Properties, in the Control ID list, select DropDownList1.
The last two steps specify that the query will get the search value for the category ID from the DropDownList control you
added earlier.
15. Click Add.
16. Click OK to close the Add WHERE Clause dialog box.
17. Click Next.
18. In the Preview page, click Test Query.
The wizard displays a dialog box that prompts you for a value to use in the WHERE clause.
19. Type 4 in the box and click OK.
The products records for category 4 are displayed.
20. Click Finish to close the wizard.
You can now test the master/detail display.
To test the page
1. Press CTRL+F5 to run the page.
When the page appears, products from the first item in the drop-down list are displayed.
2. Select a category from the list and confirm that the corresponding products appear in the grid.
Displaying Master/Detail Data on the Same Page
In this part of the walkthrough, you will display data from related tables in one page. The master table data is displayed in a
grid where users can select individual rows. When they do, one or more detail records are displayed in a scrollable control
elsewhere on the page. For illustration purposes, you will use the Northwind Categories table as the master table and the
Products table as the details table.
To display the master records
1. Add a new page to the Web site and name it MasterDetails2.aspx.
2. Switch to Design view.
3. Type Master/Detail Page in the page and format the text as a heading.
4. From the Data group of the Toolbox, drag a GridView control onto the page.
5. In the GridView Tasks menu, in the Choose Data Source list, click <New Data Source> and then use these steps to
configure a data source for the GridView control:
a. Select Database.
b. Click OK.
c. From the connection drop-down list, select the connection you created and stored earlier in the walkthrough
(NorthwindConnectionString).
d. Click Next.
e. From the Name list, select Categories.
f. In the Columns box, select CategoryID and CategoryName.
g. Click Next and then click Finish.
6. Select the GridView control, and in the GridView Tasks menu, choose Edit Columns.
The Fields dialog box is displayed.
7. Under Available Fields, open the Command Field node, choose Select, and then click Add to add it to the Selected
Fields list.
8. In the Selected Fields list, choose Select, and then in the CommandField property grid, set its SelectText property to
Details.
9. Click OK to close the Fields dialog box.
A new column with a Details hyperlink is added to the grid.
10. Select the GridView control and in the Properties window, be sure its DataKeyNames property is set to CategoryID.
This specifies that when you select a row in the grid, ASP.NET can find the key of the currently displayed Categories
record in a known location.
The grid allows you to select an individual category. The next step is to add the DetailsView control that will display the detail
records — the products associated with the selected category. The DetailsView control will use a different SQL query to get its
data, so it requires a second data source control.
To configure a query to display related records
1. Press ENTER to make space underneath the SqlDataSource1 control on the MasterDetails2.aspx page in Details view.
2. From the Data group of the Toolbox, drag a DetailsView control onto the page.
3. Configure it to use a second data source control using the following steps:
a. From the Choose Data Source list, select <New Data Source>.
b. Select Database.
c. Click OK.
d. In the connection drop-down list, click the connection you created and stored earlier in the walkthrough.
e. Click Next.
f. From the Name list under Table or View Options, select Products.
g. In the Columns box, select ProductID, ProductName, and CategoryID.
h. Click WHERE.
The Add WHERE Clause dialog box is displayed.
i. From the Column list, select CategoryID.
j. From the Operator list, select =.
k. From the Source list, select Control.
l. Under Parameter Properties, in the Control ID list, select GridView1. The query for the second grid will get its
parameter value from the selection in the first grid.
m. Click Add and then click OK to close the Add WHERE Clause dialog box.
n. Click Next.
o. In the Preview page, click Test Query.
The wizard displays a dialog box that prompts you for a value to use in the WHERE clause.
p. Type 4 in the box and click OK.
The products records for category 4 are displayed.
q. Click Finish.
4. In the DetailsView Tasks menu, check Enable Paging.
This will allow you to scroll through individual product records.
5. Optionally, in the Properties window, open the PagerSettings node and select a different Mode value.
By default, you page through records by clicking a page number, but you can select options to use next and previous
links.
You can now test the combination of the master grid and the details view.
To test the page
1. Press CTRL+F5 to run the page.
2. In the grid, select a category.
The DetailsView control displays a product associated with that category.
3. Use the pager links in the DetailsView control to navigate to other products for the same category.
4. In the grid, select a different category.
5. Review the products for that category in the DetailsView control.
Displaying Master/Detail Data on Separate Pages
For the final part of the walkthrough, you will create another variation — displaying master and detail records on separate
pages. The master records are again displayed in a grid that contains a hyperlink for each record. When users click the
hyperlink, they navigate to a second page where they can view detail records in a DetailsView control that displays the
complete Products record.
To display the master records
1. Add a new page to the Web site and name it MasterCustomers.aspx.
2. Switch to Design view.
3. Type Customers in the page and format the text as a heading.
4. From the Data folder of the Toolbox, drag a GridView control onto the page.
5. From the GridView Tasks menu on the control, choose <New Data Source> from the Choose Data Source list and
then use the wizard to do the following:
Click Database.
Connect to the Northwind database (connection NorthwindConnectionString).
Retrieve the CustomerID, CompanyName, and City columns from the Customers table.
6. Optionally, on the GridView Tasks menu, select the Enable paging check box.
7. In the GridView Tasks menu, choose Edit Columns.
The Fields dialog box is displayed.
8. Clear the Auto-Generate Fields check box.
9. Under Available Fields, choose HyperLink Field, click Add, and then set the following properties:
Property Value
Text Details

DataNavigat CustomerID
eUrlFields
This indicates that the hyperlink should get its value from the CustomerID column

DataNavigat DetailsOrders.aspx?custid={0}
eUrlFormatSt
ring This creates a link that is hard-coded to navigate to the DetailsOrders.aspx page. The link also passes a qu
ery string variable named custid whose value will be filled using the column referenced in the DataNavi
gateUrlFields property.

10. Click OK to close the Fields dialog box.


You can now create the details page that accepts a value from the master page.
To create the details page
1. Add a new page to the Web site and name it DetailsOrders.aspx.
2. Switch to Design view.
3. Type Orders in the page and format the text as a heading.
4. From the Data folder of the Toolbox, drag a GridView control onto the page.
5. In the GridView Tasks menu on the control, select <New Data Source> from the Choose Data Source list
6. In the Select a data source type list, click Database and then click OK.
7. From the connection list, select the connection you created and stored earlier in the walkthrough
(NorthwindConnectionString).
8. Click Next.
The wizard displays a page where you can create a SQL statement.
9. From the Name list, select Orders.
10. In the Columns box, select OrderID, CustomerID, and OrderDate.
11. Click WHERE.
12. From the Columns list, select CustomerID.
13. From the Operators list, select =.
14. From the Source list, select QueryString.
This specifies that the query will select records based on the value passed into the page with the query string.
15. Under Parameter Properties, in the QueryString field box, type custid.
The query will get the customer ID value from the query string, which is created when you click a Details link in the
MasterCustomers.aspx page.
16. Click Add.
17. Click OK to close the Add WHERE Clause dialog box.
18. Click Next, and then click Finish to close the wizard.
19. From the Standard node of the Toolbox, drag a Hyperlink control onto the page. Set its Text property to Return to
Customers and its NavigateUrl property to MasterCustomers.aspx.
You can now test the related master-detail pages.
To test the pages
1. Switch to the MasterCustomers.aspx page.
2. Press CTRL+F5 to run the page.
3. Click the Details link for a customer.
The browser displays the DetailsOrders.aspx page with the order for the selected customer. Note that the URL in the
browser's Address box is:

DetailsOrder.aspx?custid=x

where x is the ID of the customer you selected.


4. Click the Return to Customers link, select a different customer, and click the Details link again to test that you can view
orders for any customer.
Next Steps
This walkthrough has illustrated various ways to display data from related tables. All the scenarios have the following in
common: they rely on a parameterized query, and the parameter values can be passed to the query automatically at run time.
You might want to experiment with additional ways to use related data. For example, you might want to:
Experiment with parameters that get their values from other sources, such as a Session variable or a cookie. For more
information, see Using Parameters with Data Source Controls.
Expand what you can do with the DetailsView control from the second part of the walkthrough. For example, you can
configure the control to allow users to edit detail records. For details, see
Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control.
See Also
Concepts
Data Source Controls Overview
Modifying Data using Data Source Controls
Visual Web Developer

Walkthrough: Data Binding Web Pages with a Visual Studio


Data Component
Many Web applications are built by using multiple tiers, with one or more components in the middle tier that combine data
access together with business logic. This walkthrough shows you how to build a data-access component in a Web site and bind
a Web server control (a GridView control) to the data that is managed by the component. The data component interacts with a
Microsoft SQL Server database, and can both read and write data.
Tasks illustrated in this walkthrough include the following:
Creating a component that can read and write data.
Referencing the data component as a data source on a Web page.
Binding a control to the data that is returned by the data component.
Reading and writing data using the data component.
Prerequisites
In order to complete this walkthrough, you will need the following:
Access to the SQL Server Northwind database. For information about downloading and installing the SQL Server sample
Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site.
Note
If you need information about how to log on to the computer running SQL Server, contact the server administrator.

Microsoft Data Access Components (MDAC) version 2.7 or later.


If you are using Microsoft Windows XP or Windows Server 2003, you already have MDAC 2.7. However, if you using
Microsoft Windows 2000, you might to have to upgrade the MDAC version that is already installed on the computer. To
download the current MDAC version, see the Data Access and Storage Developer Center.
Creating the Web Site
If you have already created a Web site in Visual Web Developer by completing
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and go to the next section.
Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the left-most Location list, click File System, and then in the right-most Location textbox, enter the name of the folder
where you want to keep the pages of the Web site.
For example, type the folder name C:\WebSites\ComponentSample.
5. In the Language list, click the programming language that you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating a Data-Access Component
In this walkthrough, you will use a wizard to generate a component that reads data from and writes data to the Northwind
database. The component includes a schema file (.xsd) describing the data that you want and the methods that will be used to
read and write data. You will not have to write any code. At run time, the .xsd file is compiled into an assembly that performs
the tasks that you specify in the wizard.
To create a data-access component
1. If the Web site does not already have an App_Code folder, do the following:
a. In Solution Explorer, right-click the name of the Web site.
b. Point to Add Folder, and then click App_Code Folder.
2. Right-click the App_Code folder, and then click Add New Item.
The Add New Item dialog box appears.
3. Under Visual Studio installed templates, click DataSet.
4. In the Name box, type EmployeesObject, and then click Add.
The TableAdapter Configuration wizard appears.
5. Click New Connection.
6. If the Choose Data Source dialog box appears, click Microsoft SQL Server and then click Continue.
7. In the Server name box, enter the name of the computer that is running SQL Server.
8. For the logon credentials, select the option that is appropriate for accessing the SQL Server database (integrated security
or specific ID and password) and if it is required, enter a user name and password.
If you specify explicit credentials, select the Save my password check box.
9. Click Select or enter a database name, and then enter Northwind.
10. Click Test connection, and when you are sure that the connection works, click OK.
The TableAdapter Configuration wizard appears with the connection information filled in.
11. Click Next.
A page where you can choose to store the connection string in the configuration file appears.
12. Select the Yes, save this connection as check box, and then click Next.
You can leave the default connection string name.
A page where you can choose to use SQL statements or stored procedures appears.
13. Click Use SQL statements, and then click Next.
Using stored procedures has some advantages, including performance and security. However, for simplicity in this
walkthrough, you will use an SQL statement.
A page where you can define the SQL statement appears.
14. Under What data should be loaded into the table, type the following SQL statement:

SELECT EmployeeID, LastName, FirstName, HireDate FROM Employees

Note
You can click Query Builder to use a builder tool, if you prefer.

15. Click Next.


A page where you can define the methods that the component will expose appears.
16. Click to clear the Fill a DataTable check box, and then select the Return a DataTable and Create methods to send
updates directly to the database check boxes.
You do not need a method to fill a data table for this walkthrough. However, you will need a method that returns the data
and you also want the component to contain methods that update the database.
17. In the Method Name box, type GetEmployees.
You are naming the method that will be used later to obtain data.
18. Click Finish.
The wizard configures the component and displays it in the component designer, displaying the data that the component
manages and the methods that the component exposes.
19. Save the data component, and then close the component designer.
20. On the Build menu, click Build Web Site to make sure that the component compiles correctly.
Using the Data Component on a Page
You can now use the data component as a data source in an ASP.NET Web page. To access the data component, you will use an
ObjectDataSource control, configuring it to call the data-access methods that are exposed by the data component. You can
then add controls to the page and bind them to the data source control.
To add a data source control to the page
1. Open the Default.aspx page and switch to Design view.
2. From the Data group in the Toolbox, drag an ObjectDataSource control onto the page.
If the ObjectDataSource Tasks shortcut menu does not appear, right-click the ObjectDataSource control, and
then click Show Smart Tag.
3. On the ObjectDataSource Tasks shortcut menu, click Configure Data Source.
The Configure Data Source wizard appears.
4. In the Choose your business object list, click EmployeesObjectTableAdapters.EmployeesTableAdapter.
This is the type name (namespace and class name) of the component that you created in the preceding section.
5. Click Next.
6. On the Select tab, in the Choose a method list, click GetEmployees(), returns EmployeesDataTable.
The GetEmployees method is a method that was defined in the component that you created in the preceding section. It
returns the results of the SQL statement, available in a DataTable object that data controls can bind to.
7. Click Finish.
You can now add data controls to the page and bind them to the ObjectDataSource control. In this walkthrough, you will
work with the GridView control.
To add a GridView control to the page and bind it to the data
1. From the Data group in the Toolbox, drag a GridView control onto the page.
If the GridView Tasks shortcut menu does not appear, right-click the GridView control, and then click Show
Smart Tag.
2. On the GridView Tasks shortcut menu, in the Choose Data Source list, click ObjectDataSource1, which is the ID of
the control that you configured in the preceding section.
The GridView control reappears with a column for each data column that is returned by the SQL statement.
3. In Properties, verify that the DataKeyNames is set to EmployeeID.
Testing the Page
Now that all controls that you need are on the page, you can test the page.
To test the page
1. Press CTRL+F5 to run the page.
2. Confirm that the EmployeeID, LastName, FirstName, and HireDate columns from the Employees table are displayed in
the grid.
3. Close the browser.
The GridView control requests data from the ObjectDataSource control. In turn, the ObjectDataSource control creates an
instance of the data component and calls GetEmployees method for the data component. The GetEmployees method
returns a DataTable object, which the ObjectDataSource control returns to the GridView control.
Adding Updates to the Page
The data component that you created includes SQL statements to update the database (update, insert, and delete records). The
update facilities of the data component are exposed by methods that were generated automatically when the wizard created
the component. The GridView control and ObjectDataSource control can interact to automatically start the update methods.
Note
The GridView control does not support Insert.

To enable updates and deletes


1. Right-click the GridView control, and then click Show Smart Tag.
2. Select the Enable Editing check box.
3. Select the Enable Deleting check box.
Note
Enabling deletion lets you permanently remove records from the database. Do not enable deletion unless you are work
ing with expendable test data.

Testing Updates
You can now test to make sure that you can use the component to update the database.
To test updates
1. Press CTRL+F5 to run the page.
This time, the GridView control displays Edit and Delete links in each row.
2. Click the Edit link that is next to a row.
3. Make a change to the row, and then click Update.
The grid is redisplayed with the updated date.
4. Click the Delete link that is in a row.
The row is permanently deleted from the database. The grid is redisplayed without that row.
5. Close the browser.
Next Steps
This walkthrough illustrates how to work with a data component. You might want to experiment with additional features of
navigation. For example, you might want to do the following:
Create a custom data component instead of using the wizard.
For an example, see Walkthrough: Data Binding to a Custom Business Object.
Restrict which users can change the data. A typical method is to add membership and roles to the Web site, and then
establish rules that the business component can check before allowing changes to data.
For detailed information, see Walkthrough: Creating a Web Site with Membership and User Login (Visual Studio) and
Walkthrough: Managing Web Site Users with Roles.
See Also
Tasks
Walkthrough: Using Shared Code in Web Sites in Visual Web Developer
Walkthrough: Creating a Basic Web Page in Visual Web Developer
Concepts
Data Source Controls Overview
Using Parameters with Data Source Controls
Visual Web Developer

Walkthrough: Data Binding to a Custom Business Object


Many Web applications are built by using multiple tiers, with one or more components in the middle tier to provide data
access. Microsoft Visual Web Developer includes a wizard that helps you create a data component you can use as a middle-tier
data object, as described in Walkthrough: Data Binding Web Pages with a Visual Studio Data Component.
However, you might also want to build a custom business object, rather than relying on the data component created by the
wizard. Creating a custom business object allows you to implement your own business logic. This walkthrough illustrates how
to create a basic business object that you can use as a data source for ASP.NET Web pages.
During this walkthrough, you will learn how to:
Create a component that can return data to a Web page. The component uses an XML file for its data.
Reference the business object as a data source on a Web page.
Bind a control to the data returned by the business object.
Read and write data by using the business object.
Prerequisites
In order to complete this walkthrough, you will need:
Visual Web Developer (Visual Studio).
The .NET Framework.
This walkthrough assumes that you have a general understanding of how to use Visual Web Developer.
Creating the Web Site
If you have already created a Web site in Visual Web Developer (for example, by following the steps in
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and go to the next section,
"Creating an XML File for Business Data." Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of your Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating an XML File for Business Data
In the following procedure, you will create a simple XML file for the business component data.
To create the XML file
1. In Solution Explorer, right-click App_Data, and then click Add New Item.
Note
Be sure you create the XML file in the App_Data folder. The App_Data folder has permissions set on it that will allow t
he Web page to read and write data to the XML file.
2. Under Visual Studio installed templates, click XML file.
3. In the Name box, type Authors.xml.
4. Click Add.
A new XML file is created that contains only the XML directive.
5. Copy the following XML data, and then paste it into the file, overwriting what is already in the file.
The XML file includes schema information that identifies the database structure of the data, including a primary-key
constraint for the key.
Note
Business components can work with data in any way that is suitable for your application. This walkthrough uses an XM
L file.

<?xml version="1.0" standalone="yes"?>


<dsPubs xmlns="http://www.tempuri.org/dsPubs.xsd">
<xs:schema id="dsPubs" targetNamespace="http://www.tempuri.org/dsPubs.xsd" xmlns:mstns
="http://www.tempuri.org/dsPubs.xsd" xmlns="http://www.tempuri.org/dsPubs.xsd" xmlns:x
s="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdat
a" attributeFormDefault="qualified" elementFormDefault="qualified">
<xs:element name="dsPubs" msdata:IsDataSet="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="authors">
<xs:complexType>
<xs:sequence>
<xs:element name="au_id" type="xs:string" />
<xs:element name="au_lname" type="xs:string" />
<xs:element name="au_fname" type="xs:string" />
<xs:element name="au_phone" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
<xs:unique name="Constraint1" msdata:PrimaryKey="true">
<xs:selector xpath=".//mstns:authors" />
<xs:field xpath="mstns:au_id" />
</xs:unique>
</xs:element>
</xs:schema>
<authors>
<au_id>172-32-1176</au_id>
<au_lname>West</au_lname>
<au_fname>Paul</au_fname>
<au_phone>408 555-0123</au_phone>
</authors>
<authors>
<au_id>213-46-8915</au_id>
<au_lname>Gray</au_lname>
<au_fname>Chris</au_fname>
<au_phone>415 555-0120</au_phone>
</authors>
</dsPubs>

6. Save the Authors.xml file, and then close it.


Creating a Component
The next step is to create a class to act as your business component. You will keep the component in the App_Code folder of
your Web site. In a real application, you can keep the component in any convenient store, including the global assembly cache.
If your Web site does not already have a directory named App_Code, you must create one.
To create an App_Code folder
In Solution Explorer, right-click the name of your Web site, click Add ASP.NET Folder, and then click App_Code.
Note
The folder must be named App_Code.

You can now add the component to your site.


To create the business component
1. In Solution Explorer, right-click the App_Code folder, and then click Add New Item.
Note
Be sure to create the new item in the App_Code folder.

The Add New Item dialog box appears.


2. Under Visual Studio installed templates, click Class.
3. In the Language box, click the programming language you prefer.
4. In the Name box, type BusinessObject.
5. Click Add.
Visual Web Developer creates the new class file and opens the code editor.
6. Copy the following code, and then paste it into the file, overwriting what is already in the file.
VB
Imports Microsoft.VisualBasic
Imports System
Imports System.Web
Imports System.Data
Namespace PubsClasses
Public Class AuthorClass
Private dsAuthors As DataSet = _
New System.Data.DataSet("ds1")
Private filePath As String = _
HttpContext.Current.Server.MapPath _
("~/App_Data/authors.xml")
Public Sub New()
dsAuthors.ReadXml(filePath, Data.XmlReadMode.ReadSchema)
End Sub

Public Function GetAuthors() As DataSet


Return dsAuthors
End Function
End Class
End Namespace

C#
using System;
using System.Web;
using System.Data;
namespace PubsClasses
{
public class AuthorClass
{
private DataSet dsAuthors = new DataSet("ds1");
private String filePath =
HttpContext.Current.Server.MapPath
("~/App_Data/Authors.xml");
public AuthorClass()
{
dsAuthors.ReadXml (filePath, XmlReadMode.ReadSchema);
}
public DataSet GetAuthors ()
{
return dsAuthors;
}
}
}

Note
Make sure the value of the filePath variable references the name of the XML file that you created previously.

When an instance of the class is created, it reads the XML file and translates it into a dataset. The class's GetAuthors
method returns the dataset.
7. Save the file. You must save the file for the next section to work properly.
Displaying Data by Using the Business Component
You can now invoke the business component in a Web page and display its data. To reference the component, you use an
ObjectDataSource control, which is specifically designed to work with objects.
To create an ObjectDataSource control that references the component
1. Switch to or open the Default.aspx page.
Note
If you do not have a Default.aspx page, you can use another page. Alternatively, you can add a new page to the Web sit
e. In Solution Explorer, right-click the name of your Web site, click Add New Item, and then add a Web Form.

2. Switch to Design view.


3. In the Toolbox, from the Data folder, drag an ObjectDataSource control onto the page.
4. In the Properties window, set ID to AuthorsObjectDataSource.
5. Right-click the ObjectDataSource control, and then click the smart tag to display the ObjectDataSource Tasks menu.
6. On the ObjectDataSource Tasks menu, click Configure Data Source.
The Configure Data Source wizard appears.
7. In the Choose your business object list, click PubsClasses.AuthorClass.
8. Click Next.
9. In the Select tab, in the Choose a method list, click GetAuthors(), returns Dataset.
The GetAuthors method is defined in the business class you created previously. It returns a dataset containing the data
from the Authors.xml file.
10. Click Finish.
The configuration information you have entered specifies that to get data from the component, the component's
GetAuthors method should be called.

Note
The name of the method you specify for the SelectMethod property is case-sensitive, even if you are programming in V
isual Basic .NET.

You can now get data from the component by using the ObjectDataSource control. You will display the data in a GridView
control on the page.
To display data from the component
1. In the Toolbox, from the Data folder, drag a GridView control onto the page.
2. Right-click the GridView control, and then click the smart tag if the Common GridView Tasks menu is not showing.
3. On the Common GridView Tasks menu, in the Choose Data Source box, click AuthorsObjectDataSource.
4. Press CTRL+F5 to run the page.
The GridView control with the XML data in it is displayed.
Inserting Data by Using the Business Component
As with other data source controls, such as the SqlDataSource control, the ObjectDataSource control supports updating
(inserting, updating, and deleting). In this section, you will modify the business component with a method that inserts an
author record. Then you will change the page so that users can type new author information and modify the
ObjectDataSource control to perform the insertion.
Note
During this part of the walkthrough, the Authors.xml file you created previously will be updated. It is important that the appli
cation have permission to write to the file at run time or the Web page will display an error when you try to update the file. If
you created the Authors.xml file in the App_Data folder, permissions are set automatically.

To modify the business component to allow inserts


1. Switch to the BusinessObject file.
2. Add the following method as the final member of AuthorClass.
VB
Public Sub InsertAuthor(ByVal au_id As String, _
ByVal au_lname As String, _
ByVal au_fname As String, ByVal au_phone As String)
Dim workRow As DataRow = dsAuthors.Tables(0).NewRow
workRow.BeginEdit()
workRow(0) = au_id
workRow(1) = au_lname
workRow(2) = au_fname
workRow(3) = au_phone
workRow.EndEdit()
dsAuthors.Tables(0).Rows.Add(workRow)
dsAuthors.WriteXml(filePath, Data.XmlWriteMode.WriteSchema)
End Sub

C#
public void InsertAuthor (String au_id, String au_lname,
String au_fname, String au_phone)
{
DataRow workRow = dsAuthors.Tables[0].NewRow ();
workRow.BeginEdit ();
workRow[0] = au_id;
workRow[1] = au_lname;
workRow[2] = au_fname;
workRow[3] = au_phone;
workRow.EndEdit ();
dsAuthors.Tables[0].Rows.Add (workRow);
dsAuthors.WriteXml (filePath, XmlWriteMode.WriteSchema);
}

Note
Pay close attention to the names of the variables used to pass author information into the method (au_id, au_lname, au
_fname, and au_phone). They must match the column names defined in the schema of the XML file you created previous
ly.

The new method takes four values to insert, which you will provide in the page as parameters. The method creates a new
row in the dataset, and then writes the updated dataset out as an XML file.
3. Save the file.
The next step is to change the page so that users can enter new author information. For the following procedure, you will use
the DetailsView control.
To add a control for inserting data
1. Switch to or open the Default.aspx page.
2. Switch to Design view.
3. In the Toolbox, from the Data folder, drag a DetailsView control onto the page.
Note
The exact layout of the page is not important.

4. On the DetailsView Tasks menu, in the Choose Data Source box, click AuthorsObjectDataSource.
Note
If the DetailsView Tasks menu is not visible, click the smart tag.

5. In the Properties window, set AutoGenerateInsertButton to true.


This causes the DetailsView control to render a New button that users can click to put the control into data-entry mode.
Finally, you must configure the ObjectDataSource control to specify what action the control should take to insert data.
To configure the data source control for inserting data
Right-click AuthorsObjectDataSource, click Properties, and then set InsertMethod to InsertAuthor.
This is the name of the method that you added to the business component.
You can now insert new authors into the XML file.
To test insertion
1. Press CTRL+F5 to run the Default.aspx page.
2. In the DetailsView control, click the New button.
The control is redisplayed with text boxes.
3. Enter new author information, and then click Insert.
The new author information is added to the XML file. The GridView control immediately reflects the new record.
Next Steps
This walkthrough illustrates how to work with a data component. You might want to experiment with additional features of
navigation. For example, you might want to:
Add update and delete functionality. To do so, you would add methods to the component. Doing so is similar to adding
the insertion logic — you add a method to the component, configure the data source control to invoke the component
method, add appropriate parameters, and add a line of code to call the Update and Delete methods of the data source
control. For details, see Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control.
Change the business component to work with database data instead of with an XML file. You do not need to make any
changes to the controls on the page.
Restrict which users can make changes to the data. A typical method is to add membership and roles to your Web site,
and then establish rules that the business component can check before allowing changes to data. For details, see
Walkthrough: Creating a Web Site with Membership and User Login (Visual Studio) and
Walkthrough: Managing Web Site Users with Roles.
See Also
Tasks
Walkthrough: Data Binding Web Pages with a Visual Studio Data Component
Walkthrough: Using Shared Code in Web Sites in Visual Web Developer
Walkthrough: Creating a Basic Web Page in Visual Web Developer
Concepts
Data Source Controls Overview
Using Parameters with Data Source Controls
Visual Web Developer

Walkthrough: Creating a Web Page to Display XML Data


Data is often made available to Web applications in XML format. However, XML data is inherently hierarchical, and you might
want to be able to use the XML data in list-based controls, such as the GridView or DropDownList control. This walkthrough
shows you how to work with XML data as if it were in a tabular database table.
During this walkthrough, you will learn how to:
Use a data source control to read XML data and make it available to list controls.
Bind the GridView and DataList controls to XML data.
Create a master-detail page that displays logically related XML data.
Apply a transformation to an .xml file to make the file usable as tabular data.
Note
You can also work with XML in hierarchical form. For details, see
Walkthrough: Displaying Hierarchical Data in a TreeView Control.

Prerequisites
In order to complete this walkthrough, you will need:
Microsoft Visual Web Developer
The .NET Framework
This walkthrough assumes that you know how to use Visual Web Developer.
Creating a Web Site
If you have already created a Web site in Visual Web Developer (for example, by following the steps in
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and skip to the next section.
Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, point to New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, click File System, and then enter the name of the folder where you want to keep your Web site.
For example, type the folder name C:\WebSites\XMLWalkthrough.
5. In the Language list, click the programming language you prefer to work in, such as Visual Basic or Visual C#.
The programming language you choose will be the default for your Web site, but you can set the programming language
for each page individually.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating an .xml file for Data
To have XML data to work with, create an .xml file in the Web site.
To create the .xml file
1. In Solution Explorer, right-click the App_Data folder, and then click Add New Item.
Note
When you put the .xml file in the App_Data folder, the .xml file has the correct permissions to allow ASP.NET to read fro
m and write to the file at run time. In addition, keeping files in the App_Data folder protects them from being viewed in
a browser, because the App_Data folder is marked as non-browsable.

2. Under Visual Studio installed templates, click XML file.


3. In the Name box, type Bookstore.xml.
4. Click Add.
A new .xml file is created containing only the XML directive.
5. Copy the following XML data, and then paste it into the file, overwriting what is already in the file.

<?xml version="1.0" standalone="yes"?>


<bookstore>
<book ISBN="10-000000-001"
title="The Iliad and The Odyssey"
price="12.95">
<comments>
<userComment rating="4"
comment="Best translation I've read." />
<userComment rating="2"
comment="I like other versions better." />
</comments>
</book>
<book ISBN="10-000000-999"
title="Anthology of World Literature"
price="24.95">
<comments>
<userComment rating="3"
comment="Needs more modern literature." />
<userComment rating="4"
comment="Excellent overview of world literature." />
</comments>
</book>
<book ISBN="11-000000-002"
title="Computer Dictionary"
price="24.95" >
<comments>
<userComment rating="3"
comment="A valuable resource." />
</comments>
</book>
<book ISBN="11-000000-003"
title="Cooking on a Budget"
price="23.95" >
<comments>
<userComment rating="4"
comment="Delicious!" />
</comments>
</book>
<book ISBN="11-000000-004"
title="Great Works of Art"
price="29.95" >
</book>
</bookstore>
The Bookstore.xml file contains information about books that might be available from an online bookstore. Notice the
following about the .xml file:
The property values for elements are all expressed as attributes.
The file contains a nested structure — each book can contain its property values, as well as one or more comments
as separate elements.
6. Save the Bookstore.xml file, and then close it.
Displaying XML Data in a List Control
To make data available to the controls on an ASP.NET Web page, you use a data source control.
To configure data access to the .xml file
1. Open the Default.aspx file, and then switch to Design view.
2. In the Toolbox, from the Data group, drag an XmlDataSource control onto the page.
3. On the XmlDataSource Tasks menu, click Configure Data Source.
The Configure Data Source <DataSourceName> dialog box appears.
4. In the Data file box, type ~/App_Data/Bookstore.xml.
5. Click OK.
The XmlDataSource control makes the data in the .xml file available to controls that are on the page. The data is available in
two formats: hierarchical and tabular. Controls that bind to the XmlDataSource control can get the data in the format that
works for them.
In this case, the hierarchy of the Bookstore.xml file lends itself to a relational interpretation. The two levels of the file (books and
comments) can be thought of as two related tables.
You can now display the XML data in a list control. To begin, display some of the XML data in a GridView control.
To use a GridView control for basic display of XML data
1. In the Toolbox, from the Data group, drag a GridView control onto the page.
2. On the GridView Tasks menu, in the Choose Data Source list, click XmlDataSource1.
3. Press CTRL+F5 to run the page.
The page displays the XML data in a grid.
The data displayed in the GridView control illustrates the following points about how the XML data is interpreted:
When the XML data is represented as a data record, by default, the columns are created from attributes (such as ISBN).
Child elements are treated as part of a separate related table. For this example, the GridView control does not bind to the
comments elements in the file.
Filtering XML Data Using an XPath Expression
In the first part of this walkthrough, you relied on the default behavior of the XmlDataSource and GridView controls to
extract information from the .xml file. However, the control displays only some of the XML data.
In this part of the walkthrough, you will add a second GridView control and use it to show master-detail information. Users
will be able to select an individual book in the first GridView control, and the second GridView control will display the related
user comments, if any, for that book. To display comments, you will use an XPath expression, which allows you to specify which
level of the XML data file you want to extract. Because you want to display comments for a specific book only, you will create
the XPath expression dynamically, depending on which book the user has selected.
To begin, you will add a second GridView control to the page, and then configure the GridView control so that it will display
user comments.
To add a GridView control to display user comments
1. Switch to Design view.
2. In the Toolbox, from the Data group, drag a GridView control onto the page and place it below the first GridView
control.
The GridView Tasks menu appears.
3. In the Choose Data Source box, click New data source.
The Data Source Configuration Wizard appears.
4. Click XML File as the data source.
5. In the Specify an ID for the data source box, leave the default, XmlDataSource2.
6. Click OK.
The Configure Data Source dialog box appears.
7. In the Data file box, type ~/App_Data/Bookstore.xml.
You will use the same .xml file that you used previously in this walkthrough, but you will extract different information
from it for the second GridView control.
8. In the XPath Expression box, type the following expression:
/bookstore/book/comments/userComment
Later, you will change the XPath property dynamically in code. However, by defining an XPath expression for the data
source now, you will help the tools in Visual Web Designer determine what information will ultimately be displayed in
the control.
9. Click OK.
The second GridView control appears, showing ratings and user comments as sample data.
10. Select the GridView2 control, and in Properties, set Visible to False.
The second GridView control will appear only when the user has selected a book in the first GridView control.
You can now configure the first GridView control to allow users to select a book. You will also add code that creates an XPath
expression based on the user's selection and assigns it to the XmlDataSource2 control. The end result is that the second
GridView control will display the user comments for the selected book.
To configure the GridView control for selection
1. Switch to Design view, and then select the first GridView control.
2. On the GridView Tasks menu, select Enable Selection.
A new column is added to the GridView control containing a link button with the text Select.
3. In Properties, set DataKeyNames to ISBN.
You can click the property box to select the value.
This configures the GridView control to treat the ISBN property as the primary key for each element in the XML data.
4. Click the GridView control. In the Properties window, select Events from the drop-down list at the top of the
Properties window. This will display all events associated with the control.
5. Double-click the box for the SelectedIndexChanged event.
This switches you to the code editor and creates a skeleton handler for the SelectedIndexChanged event.
6. Add the following highlighted code to the handler.
VB
Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles GridView1.SelectedIndexChanged
Dim currentIndex As Integer
currentIndex = GridView1.SelectedIndex
Dim isbn As String
isbn = CStr(GridView1.DataKeys(currentIndex).Value)
XmlDataSource2.XPath = _
String.Format( _
"/bookstore/book[@ISBN='{0}']/comments/userComment", _
isbn)
GridView2.Visible = true
End Sub

C#
protected void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
{
String isbn = (String)
GridView1.DataKeys[GridView1.SelectedIndex].Value;
XmlDataSource2.XPath =
String.Format(
"/bookstore/book[@ISBN='{0}']/comments/userComment",
isbn);
GridView2.Visible = true;
}

The code does the following:


It uses the SelectedIndex property (of the GridView control) to index into the array of data keys, and then return
the primary key of the selected row. Previously, you set the DataKeyNames property to contain ISBN numbers.
It creates a new XPath expression that includes the selected ISBN.
It assigns the new XPath expression to the XPath property (of the XmlDataSource2 control). Assigning a new XPath
expression to the XPath property causes the XmlDataSource control to re-evaluate the data it returns. The
GridView control, in turn, rebinds to the data.
It sets the Visible property to true, which causes the second GridView control to be displayed. You declaratively
set the visibility to false when you created the second GridView control so that it does not appear until the user
selects a book.
You can now test the page.
To test filtering with the XPath expression
1. View the Default.aspx page and press CTRL+F5 to run the page.
The page is displayed with a grid of information about books.
2. Click the Select link next to the first book.
The comments about that book are displayed in a second grid.
3. Click the Select link next to the last book.
No comments are displayed, because there are none for this book.
Displaying XML Data with a Custom Layout
To create a custom layout for data, you can use a DataList control. In the DataList control, you can define one or more
templates. Each template contains a combination of static text and controls that you can arrange in any layout you want.
In this part of the walkthrough, you will use a DataList control to display the same information that you previously displayed
using the GridView2 control. However, you will be able to create a custom layout for the user comments.
To display XML data with a custom layout
1. Switch to Design view, click the GridView2 control, and then press DELETE to remove it from the page.
2. In the Toolbox, from the Data group, drag a DataList control onto the page.
3. On the DataList Tasks menu, in the Choose Data Source list, click XmlDataSource2.
You will use the same data source for the DataList control that you used for the GridView2 control.
4. In Properties, set Visible to false.
5. If the smart tag does not appear, right-click the DataList control and then click Show Smart Tag.
6. On the DataList Tasks menu, click Edit Templates, and then in the Display box, click Item Template.
The DataList control appears with an editable region for the item template. The template contains a default layout that
consists of static text and Label controls that are bound to the Rating and Comment columns in the data record. (The
DataList control is able to infer the structure of the data that it will display because you defined a static XPath expression
for the XmlDataSource2 control earlier in this walkthrough.)
7. In the editable region, change the first caption to User rating:.
8. Change the caption comment to Comment:.
9. Right-click the title bar of the DataList control, point to Edit Template, and then click Separator Template.
Another editable region is displayed in the DataList control, this one for defining the layout of the elements that will
appear between each data record.
10. In the Toolbox, from the HTML group, drag a Horizontal Rule control onto the editable region.
11. Right-click the DataList control, and then click End Template Editing.
12. Right-click the page, and then click View Code to switch to the code for the page.
13. In the GridView1_SelectedIndexChanged handler, change the following line:
VB
GridView2.Visible = True

C#
GridView2.Visible = true;

to the following:
VB
DataList1.Visible = True

C#
DataList1.Visible = true;

You can now test the custom layout.


To test the custom layout
1. View the Default.aspx page and press CTRL+F5 to run the page.
The page is displayed with a grid of information about books.
2. Click the Select link next to the first book.
The comments about the first book are displayed in a list.
3. Click the Select link next to the last book.
No comments are displayed, because there are none for this book.
Using Transformations to Restructure XML Data
The .xml file that you have used in this walkthrough is structured so that the properties of each element are expressed as
attributes. In many cases, .xml files that you work with are structured differently. For example, values in an .xml file are often
created as elements with inner text.
If you have an .xml file in which property values are expressed in a format other than attributes, you can create a
transformation file (.xslt) that can dynamically reformat the .xml file so that it is compatible with the XmlDataSource control.
In this part of the walkthrough, you will work with an .xml file that contains the same data as the Bookstore.xml file that you
used previously. However, the data will be structured differently than it was in the Bookstore.xml file, so you will use a
transformation to dynamically reformat it.
To begin this section, you will create a second .xml file.
To create the second .xml file
1. In Solution Explorer, right-click the App_Data folder, and then click Add New Item.
2. Under Visual Studio installed templates, click XML file.
3. In the Name box, type Bookstore2.xml.
4. Click Add.
A new .xml file is created containing only the XML directive.
5. Copy the following XML data, and then paste it into the file, overwriting what is already in the file.

<?xml version="1.0" standalone="yes"?>


<bookstore>
<book ISBN="10-000000-001">
<title>The Iliad and The Odyssey</title>
<price>12.95</price>
<comments>
<userComment rating="4">
Best translation I've read.
</userComment>
<userComment rating="2">
I like other versions better.
</userComment>
</comments>
</book>
<book ISBN="10-000000-999">
<title>Anthology of World Literature</title>
<price>24.95</price>
<comments>
<userComment rating="3">
Needs more modern literature.
</userComment>
<userComment rating="4">
Excellent overview of world literature.
</userComment>
</comments>
</book>
<book ISBN="11-000000-002">
<title>Computer Dictionary</title>
<price>24.95</price>
<comments>
<userComment rating="3">
A valuable resource.
</userComment>
</comments>
</book>
<book ISBN="11-000000-003">
<title>Cooking on a Budget</title>
<price>23.95</price>
<comments>
<userComment rating="4">Delicious!</userComment>
</comments>
</book>
<book ISBN="11-000000-004">
<title>Great Works of Art</title>
<price>29.95</price>
</book>
</bookstore>

6. Save the Bookstore2.xml file, and then close it.


You now need a transformation file that will convert the data in the Bookstore2.xml file into the attribute-based format that is
used by the XmlDataSource control.
To create the transformation file
1. In Solution Explorer, right-click the App_Data folder, and then click Add New Item.
2. Under Visual Studio installed templates, click Text File.
There is no template for a transform file, so you can create it as a text file with the correct extension.
3. In the Name box, type Bookstore2.xsl.
Note
Be sure to use the .xsl extension.

4. Click Add.
A new blank file is created.
5. Copy the following transformation code, and then paste it into the file.

<?xml version="1.0"?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
>
<xsl:strip-space elements="*"/>
<xsl:output method="xml"
omit-xml-declaration="yes"
indent="yes"
standalone="yes" />

<xsl:template match="/">
<xsl:for-each select="bookstore">
<xsl:element name="bookstore">
<xsl:for-each select="book">
<xsl:element name="book">
<xsl:attribute name="ISBN">
<xsl:value-of select="@ISBN"/>
</xsl:attribute>
<xsl:attribute name="title">
<xsl:value-of select="title"/>
</xsl:attribute>
<xsl:attribute name="price">
<xsl:value-of select="price"/>
</xsl:attribute>
</xsl:element>
</xsl:for-each>
</xsl:element>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

6. Save the Bookstore2.xsl file, and then close it.


From this point, working with the XML data is very similar to what you did earlier in this walkthrough, except that you can
specify the transformation file when you configure the XmlDataSource control. For the last part of this walkthrough, you will
create a new page, and then repeat some of the steps from the first part of this walkthrough. However, this time you will show
the data from the Bookstore2.xml file.
To configure data access to the .xml file
1. In Solution Explorer, right-click the name of your Web site, and then click Add New Item.
2. Under Visual Studio installed templates, click Web Form.
3. In the Name box, type Bookstore2.aspx.
4. Click Add.
5. Switch to Design view.
6. In the Toolbox, from the Data group, drag an XmlDataSource control onto the page.
7. On the XmlDataSource Tasks menu, click Configure Data Source.
The Configure Data Source dialog box appears.
8. In the Data file box, type ~/App_Data/Bookstore2.xml.
9. In the Transform file box, type ~/App_Data/Bookstore2.xsl.
10. Click OK.
11. In the Toolbox, from the Data group, drag a GridView control onto the page.
12. On the GridView Tasks menu, in the Choose Data Source list, click XmlDataSource1.
13. Press CTRL+F5 to run the page.
The page displays the XML data in a grid. The data will appear in the grid the same as it did in the first page, even though
the format of the underlying .xml file is different this time.
Next Steps
This walkthrough has illustrated only the basics of how to work with an XML document and transformations. In a real
application, you will often need to work with the XML document in more depth. The following are suggestions for further
investigation:
Creating more sophisticated transformations. In this walkthrough, you have seen only one example of how you can use
transformations. XSL is a powerful language, with sophisticated support not just for creating HTML pages, but also for
virtually any kind of transformation from XML to another structure.
Writing XML documents (instead of simply reading them). The Xml control makes it easy to display the contents of an
XML file in an ASP.NET Web page. However, you might want to create or amend XML files yourself. For details, see
XML Documents and Data. For an example of writing to an XML file, see
Walkthrough: Displaying and Tracking Advertisements with the AdRotator Control.
See Also
Tasks
Walkthrough: Displaying Hierarchical Data in a TreeView Control
Walkthrough: Creating a Basic Web Page in Visual Web Developer
Visual Web Developer

Walkthrough: Displaying Hierarchical Data in a TreeView


Control
The ASP.NET TreeView control is designed to present users with data in a hierarchical structure. Users can open individual
nodes that can in turn contain child nodes. The TreeView control is suitable for displaying XML data, but can be used for any
data that can be represented in a hierarchy. This walkthrough shows you the basics of using the TreeView control and various
ways to display hierarchical data.
Tasks illustrated in this walkthrough include:
Using the TreeView control to display XML data.
Customizing the display of the TreeView control.
Displaying records from related database tables in the TreeView control.
Prerequisites
In order to complete this walkthrough, you will need:
Microsoft Visual Web Developer (Visual Studio).
Microsoft Data Access Components (MDAC) version 2.7 or later.
If you are using Microsoft Windows XP or Windows Server 2003, you already have MDAC 2.7. However, if you are using
Microsoft Windows 2000, you might need to upgrade the MDAC already installed on your computer. For more
information, see "Microsoft Data Access Components (MDAC) Installation" in the MSDN Library.
Access to the SQL Server Northwind database. For information about downloading and installing the SQL Server sample
Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site.
Note
If you need information about how to log on to the computer running SQL Server, contact the server administrator.

A user name and password for a SQL Server account that has access to the Northwind database, if the SQL Server
database is not on the same computer as the Web server.
Creating the Web Site
Create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New, and then click Web Site. If you are using Visual Web Developer Express, on the File menu,
click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, select File System, and enter the name of the folder where you want to keep the pages of your Web
site.
For example, type the folder name C:\WebSites\HierarchicalData.
5. In the Language list, click the programming language you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating an XML File for Data
Create a new XML file by following these steps.
To create the XML file
1. In Solution Explorer, right-click the Web site, and then click Add New Item.
2. In the Add New Item dialog box, under Standard Templates, click XML File.
3. In the Name box, type Bookstore.xml, and then click Add.
Visual Web Developer creates the new Bookstore.xml file and opens the code editor.
4. Copy the following XML data, and then paste it into the Bookstore.xml file, overwriting what is already in the file.

<?xml version="1.0" standalone="yes"?>


<bookstore>
<genre name="fiction">
<book ISBN="10-000000-001">
<title>The Iliad and The Odyssey</title>
<price>12.95</price>
<comments>
<userComment rating="4">
Best translation I've read.
</userComment>
<userComment rating="2">
I like other versions better.
</userComment>
</comments>
</book>
<book ISBN="10-000000-999">
<title>Anthology of World Literature</title>
<price>24.95</price>
<comments>
<userComment rating="3">
Needs more modern literature.
</userComment>
<userComment rating="4">
Excellent overview of world literature.
</userComment>
</comments>
</book>
</genre>
<genre name="nonfiction">
<book ISBN="11-000000-002">
<title>Computer Dictionary</title>
<price>24.95</price>
<comments>
<userComment rating="3">A valuable resource.</userComment>
</comments>
</book>
<book ISBN="11-000000-003">
<title>Cooking on a Budget</title>
<price>23.95</price>
<comments>
<userComment rating="4">Delicious!</userComment>
</comments>
</book>
</genre>
</bookstore>

The XML file contains information about books that might be available from an online bookstore.
5. Save the Bookstore.xml file, and then close it.
Displaying XML Data in the TreeView Control
In this section, you will use the TreeView control to display the XML data. To begin, you can display the XML information
without any special configuration.
To display the XML data
1. Open the Default.aspx page, and then switch to Design view.
2. In the Toolbox, from the Navigation group, drag a TreeView control onto the page.
3. Right-click the TreeView control, and then click Show Smart Tag.
4. On the TreeView Tasks menu, in the Choose Data Source drop-down list, select New Data Source. The Data Source
Configuration Wizard appears.
5. In the Where will the application get data from? window, select XML File. Leave the default ID for the data source.
Click OK.
6. In the Configure Data Source dialog box, in the Data file box, enter ~/Bookstore.xml, and then click OK.
You can now test the page.
To test the page
1. Press CTRL+F5 to run the page.
2. Collapse, and then expand, the nodes in the control.
By default, the nodes display only the tag names of the elements in the Bookstore.xml file.
You can customize the information displayed in the TreeView control by creating custom bindings, which allow you to specify
what information from the XML file to display for each node.
To create custom bindings
1. On the Default.aspx page, right-click the TreeView control, and then click Show Smart Tag.
2. On the TreeView Tasks menu, click Edit TreeNode Databindings.
The TreeView DataBindings Editor dialog box appears.
3. Clear the Auto generate data bindings check box, because you will define the data bindings.
4. Click Add to create a new binding, and then, under Data binding properties, set DataMember to bookstore and set
Text to Book Information.
You are configuring the binding to display a static value, because the Bookstore node is the top-most node in the .xml
file and appears only once in the TreeView control.
5. Click Add to create a second binding, and then, under Data binding properties, set DataMember to genre and
TextField to name.
This specifies that the node will read the <genre> element in the .xml file and assign its name attribute to the TextField
property.
6. Click Add to create a third binding for books, and then, under DataBinding Properties, set DataMember to book and
TextField to ISBN.
7. Click OK.
You can now test the page.
To test the page
Press CTRL+F5 to run the page.
This time, the TreeView control displays the three levels corresponding to the bindings that you have defined. The three
levels are the root node, labeled Book Information, the genre groups, and the ISBN details.
You can create a data binding for any element in an XML file, but you can bind only to the attributes of the element, the inner
text, the name of the element, or the value of the element. You cannot bind to any of the nested elements. To display values in
the nested elements, you create separate bindings to those elements. An alternative method is to transform the XML file using
XSLT, so that the inner elements are converted to attributes. For more information and an example, see the
System.Web.UI.WebControls.XmlDataSource.TransformFile property.
Displaying Relational Data in the TreeView Control
The TreeView control can display any type of hierarchical data, even if the data hierarchy is logical, as in a database, and not
physical, as in an XML file. In this section, you will use the TreeView control to display data from related tables in the
Northwind database.
To start, you will create a connection to the computer running SQL Server where you have the Northwind database.
To create a connection to SQL Server
1. In Server Explorer, right-click Data Connections, and then click Add Connection. If you are using Visual Web
Developer Express, use Database Explorer.
The Add Connection dialog box appears.
If the Data source list does not display Microsoft SQL Server (SqlClient), click Change, and in the Change Data
Source dialog box, select Microsoft SQL Server.
If the Choose Data Source page appears, in the Data source list, select the type of data source you will use. For
this walkthrough, the data source type is Microsoft SQL Server. In the Data provider list, click .NET Framework
Data Provider for SQL Server, and then click Continue.
Note
If the Server Explorer tab is not visible in Visual Web Developer, in the View menu, click Server Explorer. If the Databa
se Explorer tab is not visible, in the View menu, click Database Explorer.

2. In the Add Connection box, enter your server name in the Server Name box.
3. For the Log on to the server section, select the option that is appropriate to access the running the SQL Server database
(integrated security or specific ID and password) and, if required, enter a user name and password.
4. Select the Save my Password check box.
Note
In production applications, do not use Save my Password because this embeds the user name and password in the ap
plication files.

5. Under Select or enter a database name, enter Northwind.


6. Click Test Connection, and when you are sure that it works, click OK.
Your new connection has been created under Data Connections in Server Explorer (or Database Explorer).
Configuring a TreeView Control to Display Database Data
In this section, you will dynamically populate nodes with data. The first-level nodes will represent master data — in this case,
categories. When users click a node, the child nodes for the category will be created by making a query to the database that
retrieves the products for that category. To retrieve the data, you can use a data source control. However, in this walkthrough,
you will create and execute a query programmatically.
To begin, create a new page and a new TreeView control.
To create the new page and TreeView control
1. Add an ASP.NET Web page (Web Form page) named TreeViewDynamic.aspx to your Web site.
2. Open the TreeViewDynamic.aspx page, switch to Design view, and then in the Toolbox, from the Standard group, drag a
Label control onto the page and name it labelStatus.
The labelStatus control is used for error reporting only.
3. In the Toolbox, from the Navigation group, drag a TreeView control onto the page.
4. Right-click the TreeView control, click Properties, and then set MaxDataBindDepth to 2.
5. Right-click the TreeView control, click Show Smart Tasks, and then on the TreeView Tasks menu, click Edit Nodes.
6. In the TreeView Node Editor dialog box, click the icon labeled Add a root node, and then, under Properties, set Text
to Product List and PopulateOnDemand to true.
7. Click OK.
You are creating the topmost node of the tree, which contains only static text.
To configure the Web.config file
1. In the Toolbox, from the Data group, drag a SqlDataSource control onto the page.
2. Select the SqlDataSource control, and then click Show Smart Tag.
3. On the SqlDataSource Tasks menu, click Configure Data Source.
The Configure Data Source - SqlDataSource1 wizard displays a page in which you can choose a connection.
4. In the Which data connection should your application use to connect to the database? box, enter the connection
that you created in "To create a connection to SQL Server," and then click Next.
The wizard displays a page in which you can choose to store the connection string in a configuration file. Storing the
connection string in the configuration file has two advantages:
It is more secure than storing it in the page.
You can use the same connection string in multiple pages.
5. Select the Yes, save this connection as check box, and then click Next.
The wizard displays a page in which you can specify what data you want to retrieve from the database.
6. Under Specify columns from a table or view, in the Name box, click Categories.
7. Under Columns, select the CategoryID and CategoryName boxes.
8. Click Next.
9. Click Finish.
You will use the connection string created in the Web.config file later, in the RunQuery method defined later in this
walkthrough. You will not use the SqlDataSource control.
Now, you will add code to populate the control's child nodes when users click the node. To add nodes dynamically, you create
an event handler for the TreeNodePopulate event.
To create the event handler
1. Right-click the TreeView control, and then in Properties, click the Events icon.
2. Double-click the box for the TreeNodePopulate event.
Visual Web Developer switches to Source view.
3. Add the following highlighted code to the handler.
VB
Protected Sub TreeView1_TreeNodePopulate(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) _
Handles TreeView1.TreeNodePopulate
If e.Node.ChildNodes.Count = 0 Then
Select Case e.Node.Depth
Case 0
PopulateCategories(e.Node)
Case 1
PopulateProducts(e.Node)
End Select
End If
End Sub

C#
protected void TreeView1_TreeNodePopulate(
object sender, TreeNodeEventArgs e)
{
if (e.Node.ChildNodes.Count == 0)
{
switch (e.Node.Depth)
{
case 0:
PopulateCategories(e.Node);
break;
case 1:
PopulateProducts(e.Node);
break;
}
}
}

This code is called when a user clicks a node to open it. Because you want to display different data at different levels of
the tree, you must determine which node depth the user has clicked, and then populate the nodes at that level
appropriately. In this walkthrough, the PopulateCategories method is called if the user clicks the root node (depth 0).
The PopulateProducts method is called if the user clicks a category name (depth 1). The methods are shown in the next
section.
The TreeNodeEventArgs object provides programmatic access to the current node. To populate the node, you add
elements to it. In the example code, the node is passed to the method that will add the child nodes.
Reading Node Data from the Database
The information to display in each node comes from the database. You must write the code that performs the database query,
reads the records, and creates a node for each record. This walkthrough assumes that you are working with the SQL Server
Northwind sample database, so you must use ADO.NET objects from the System.Data.SqlClient namespace.
For the first level of nodes (level 0), you will display a list of all available categories. The code you create calls a RunQuery
method that you will create later in the walkthrough.
To add nodes for all categories
1. Switch to Source view.
2. If you are working with a single-file page, add the following directives to the top of the code page.

<%@ Import Namespace="System.Data" %>


<%@ Import Namespace="System.Data.SqlClient" %>

Importing the namespaces will make it easier to write the code you need.
3. If you are working with a code-behind page, switch to the code-behind page (TreeViewDynamic.aspx.vb or
TreeViewDynamic.aspx.cs) and add the following lines to the top of the code file, outside the class declaration.
VB
Imports System.Data
Imports System.Data.SqlClient

C#
using System.Data;
using System.Data.SqlClient;

4. Make sure the page is still in Source view.


5. Add the following method to the page code.
VB
Sub PopulateCategories(ByVal node As TreeNode)
Dim sqlQuery As New SqlCommand( _
"Select CategoryName, CategoryID From Categories")
Dim ResultSet As DataSet
ResultSet = RunQuery(sqlQuery)
If ResultSet.Tables.Count > 0 Then
Dim row As DataRow
For Each row In ResultSet.Tables(0).Rows
Dim NewNode As TreeNode = New _
TreeNode(row("CategoryName").ToString(), _
row("CategoryID").ToString())
NewNode.PopulateOnDemand = True
NewNode.SelectAction = TreeNodeSelectAction.Expand
node.ChildNodes.Add(NewNode)
Next
End If
End Sub

C#
void PopulateCategories(TreeNode node)
{
SqlCommand sqlQuery = new SqlCommand(
"Select CategoryName, CategoryID From Categories");
DataSet resultSet;
resultSet = RunQuery(sqlQuery);
if (resultSet.Tables.Count > 0)
{
foreach (DataRow row in resultSet.Tables[0].Rows)
{
TreeNode NewNode = new
TreeNode(row["CategoryName"].ToString(),
row["CategoryID"].ToString());
NewNode.PopulateOnDemand = true;
NewNode.SelectAction = TreeNodeSelectAction.Expand;
node.ChildNodes.Add(NewNode);
}
}
}

The code creates a SqlCommand object that encapsulates the text of the query. It passes the object to a method (which
you will write) that performs the database query and returns a DataSet object. The code then loops through the records
in the DataSet object and creates a new node for each record, setting the text and value of the node with database
information. Then, the code sets the PopulateOnDemand property of each node to true so that the node will raise its
TreeNodePopulate event when clicked. The SelectAction property is set so that the nodes are expanded by default.
The second level of nodes will display the products for each category. For this reason, populating the products nodes requires a
parameterized query so that you can retrieve the products for the current category and populate the child nodes appropriately.
To add nodes for products
Add the following method to the page code.
VB
Sub PopulateProducts(ByVal node As TreeNode)
Dim sqlQuery As New SqlCommand
sqlQuery.CommandText = "Select ProductName From Products " & _
" Where CategoryID = @categoryid"
sqlQuery.Parameters.Add("@categoryid", SqlDbType.Int).Value = _
node.Value
Dim ResultSet As DataSet = RunQuery(sqlQuery)
If ResultSet.Tables.Count > 0 Then
Dim row As DataRow
For Each row In ResultSet.Tables(0).Rows
Dim NewNode As TreeNode = New _
TreeNode(row("ProductName").ToString())
NewNode.PopulateOnDemand = False
NewNode.SelectAction = TreeNodeSelectAction.None
node.ChildNodes.Add(NewNode)
Next
End If
End Sub

C#
void PopulateProducts(TreeNode node)
{
SqlCommand sqlQuery = new SqlCommand();
sqlQuery.CommandText = "Select ProductName From Products " +
" Where CategoryID = @categoryid";
sqlQuery.Parameters.Add("@categoryid", SqlDbType.Int).Value =
node.Value;
DataSet ResultSet = RunQuery(sqlQuery);
if (ResultSet.Tables.Count > 0)
{
foreach (DataRow row in ResultSet.Tables[0].Rows)
{
TreeNode NewNode = new
TreeNode(row["ProductName"].ToString());
NewNode.PopulateOnDemand = false;
NewNode.SelectAction = TreeNodeSelectAction.None;
node.ChildNodes.Add(NewNode);
}
}
}

This code is similar to the code used to populate the categories node. One difference is that the SqlCommand object is
configured with a parameter that is set at run time with the value of the node that the user clicked; that is, of the selected
category. Another difference is that the PopulateOnDemand property is set to false. This causes the products nodes to
be displayed without an expansion button, which is necessary because there are no more nodes below products.
The final step is to create the method that performs the query and returns the dataset.
To perform the query
Add the following subroutine to the page.
VB
Function RunQuery(ByVal sqlQuery As SqlCommand) As DataSet
Dim connectionString As String
connectionString = _
ConfigurationManager.ConnectionStrings _
("NorthwindConnectionString").ConnectionString
Dim dbConnection As New SqlConnection
dbConnection.ConnectionString = connectionString
Dim dbAdapter As New SqlDataAdapter
dbAdapter.SelectCommand = sqlQuery
sqlQuery.Connection = dbConnection
Dim resultsDataSet As DataSet = New DataSet
Try
dbAdapter.Fill(resultsDataSet)
Catch ex As Exception
labelStatus.Text = "Unable to connect to SQL Server."
End Try
Return resultsDataSet
End Function

C#
private DataSet RunQuery(SqlCommand sqlQuery)
{
string connectionString =
ConfigurationManager.ConnectionStrings
["NorthwindConnectionString"].ConnectionString;
SqlConnection DBConnection =
new SqlConnection(connectionString);
SqlDataAdapter dbAdapter = new SqlDataAdapter();
dbAdapter.SelectCommand = sqlQuery;
sqlQuery.Connection = DBConnection;
DataSet resultsDataSet = new DataSet();
try
{
dbAdapter.Fill(resultsDataSet);
}
catch
{
labelStatus.Text = "Unable to connect to SQL Server.";
}
return resultsDataSet;
}

This code creates a data adapter based on the SqlCommand object passed to it. Then, it creates and populates a dataset
with the adapter.
You can now test the page.
To test the page
1. Press CTRL+F5 to run the page.
The TreeView control is displayed with a list of categories and products.
2. Click a category to confirm that it collapses and expands to show a list of products for each category.
Next Steps
This walkthrough used both hierarchical XML data and a relational database to populate a TreeView control. You can use the
TreeView control to work with site navigation information and XML data as tabular (list) data.
For details on site navigation, see Walkthrough: Adding Site Navigation to a Web Site.
For details on working more with XML data, see Walkthrough: Creating a Web Page to Display XML Data.
See Also
Tasks
Walkthrough: Creating a Web Page to Display XML Data
How to: Secure Connection Strings When Using Data Source Controls
Visual Web Developer

Walkthrough: Using Output Caching to Enhance Web Site


Performance
Performance is a critical aspect of any Web application. Decreasing the amount of processing a Web server must do to comply
with individual requests results in quicker response times, the server's ability to handle more concurrent requests, and a
reduced load on intermediate and back-end data systems.
One way to achieve better performance with ASP.NET is by using output caching to reduce server workload. Output caching is
an optimization that reduces Web server response time.
Normally, when a browser requests an ASP.NET page, ASP.NET creates an instance of the page, runs any code in the page, runs
database queries (if any), dynamically assembles the page, and then sends the resulting output to the browser. Output caching
allows ASP.NET to send a pre-processed copy of a page rather than go through this process for each request. This difference
cuts down the amount of processing the Web server does, which increases performance and enables greater scalability.
Tasks illustrated in this walkthrough include:
Caching pages, using either a page directive to have the entire page output cached, regardless of browser type, individual
parameters, or data.
Using application-level cache profiles, a feature that enables you to define output caching settings for an entire
application. Individual pages can associate themselves with profiles contained in your Web.config file. This enables you to
control caching centrally instead of editing each page.
Caching based on individual parameters sent with the page.
Prerequisites
In order to complete this walkthrough, you will need:
Visual Web Developer (Visual Studio).
Microsoft .NET Framework version 2.0.
Creating the Web Site
If you have already created a Web site in Visual Web Developer (see
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and go to the next topic in this
walkthrough. Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site. (In Visual Web Developer Express Edition, on the File menu, click New, and then
click Web Site.)
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, select ASP.NET Web Site.
4. In the Location box, type the name of the folder where you want to keep the pages of your Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, select the programming language that you prefer to work in.
6. Click OK.
7. Visual Web Developer creates the folder and a new page named Default.aspx.
Configuring Page-Level Caching
This procedure introduces you to basic page caching. In this procedure, you will add a Label control to your page that displays
the time when the page was created, and then configure the page to be cached. By displaying the page's creation time you can
see that the page request is fulfilled from the cache.
To configure page-level caching
1. Open or switch to the Default.aspx page. (Alternatively, you can use any other page in your Web site.)
2. Switch to Design view.
3. From the Standard group in the toolbox, drag a Label control to your page, leaving the default name of Label1.
4. Double-click a blank are of the page.
The designer switches to the code editor and creates a Page_Load method.
5. Add the following highlighted code to the method:
VB
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs)
Label1.Text = System.DateTime.Now.ToString()
End Sub

C#
protected void Page_Load(Object sender, System.EventArgs e)
{
Label1.Text = System.DateTime.Now.ToString();
}

6. Press CTRL+F5 to run the page.


When the page appears in the browser, you will see the current date and time. Press your browser's refresh button and
notice that the timestamp changes each time.
7. Close the browser.
8. Add the following @ OutputCache directive to the top of the page:

<%@ OutputCache Duration="15" VaryByParam="none" %>

This directive configures the page to be cached. The Duration attribute specifies that the page will remain in the cache
for 15 seconds.
9. Press CTRL+F5 to run the page again.
10. Refresh the page several times.
Notice that the time display is updated only every 15 seconds, regardless of how many times you refresh the browser.
This is because the request is fulfilled from the cache until the duration time has elapsed, at which point the page code is
executed again.
Setting Application-Level Caching
In the preceding procedure, you configured caching for an individual page. In some circumstances you might want to configure
caching for all pages in your Web site. You might also want to establish different caching rules (profiles) and apply the cache
profiles to sets of individual pages. Setting application-level caching enables you to change cache behavior from a single
configuration file rather than editing the @ OutputCache directive of individual pages. In the following procedure, you will set
up a simple cache profile and use it for the page that you were just working with.
To configure application-level caching
1. If you already have a Web.config file, go to step 4.
2. In Solution Explorer, right-click the name of your Web site, and then click Add New Item.
3. In the Add Item dialog box, click Web Configuration File, and then click Add.
Be sure that you use the name Web.config.
4. Add the following XML as a child of the system.web element:

<!-- caching section group -->


<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="AppCache1" enabled="true" duration="60"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>

5. Save the file and then close it.


6. Open or switch to the Web page you were working with, and then switch to Source view.
7. Change the @ OutputCache directive to read as follows:

<%@ OutputCache CacheProfile="AppCache1" VaryByParam="none" %>

8. Press CTRL+F5 to run the page.


9. Refresh the page a number of times.
This time the date will remain the same for the duration specified in the cache profile, which is 60 seconds.
Caching Using Parameters
The @ OutputCache directive requires you to set the VaryByParam attribute, which until you now you have set to "none".
The VaryByParam attribute enables you to configure caching so that ASP.NET stores different versions of a page depending
on parameters such as query strings, form post values, request headers, and so on.
For example, you can use cache parameters in a page that displays weather conditions for select cities, where the weather data
is refreshed only every three hours. In this scenario, you want to cache a separate version of the page for each city. You can do
so by setting the cache parameter to vary by a query string parameter.
In the following procedure, you will change the Label control you added to your page so that it displays the time with a
colored background. You can change the color by using a TextBox control for entering a color name.
When you submit the page, the color you type is submitted as post data, and the color behind the Label control changes.
When a new color is requested (when the page includes new post data), the page is regenerated and the timestamp is updated.
However, subsequent requests for the same color will result in the cached page being returned (until the duration interval has
been exceeded).
To cache based on parameters
1. Open or switch to the page you have been working on.
2. Switch to Design view.
3. From the Standard group of the toolbox, drag a TextBox control onto the page and set its ID to Color.
4. Drag a Button control onto the page, leaving the default name of Button1.
5. Set the Button control's Text property to "Change Color".
Double-click the Button control to create a Click event handler.
6. Within the method, add the following highlighted code:
VB
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Label1.BackColor = _
System.Drawing.Color.FromName(Server.HtmlEncode(Color.Text))
End Sub
C#
protected void Button1_Click(Object sender, System.EventArgs e)
{
Label1.BackColor =
System.Drawing.Color.FromName(Server.HtmlEncode(Color.Text));
}

7. Set the defaultbutton attribute of the form element to "Button1".


This causes the Click event handler for the button to be invoked when the ENTER key is pressed.
8. Replace the @ OutputCache directive with the following version:

<%@ OutputCache Location="Server" Duration="60" VaryByParam="Color" %>

9. Press CTRL+F5 to run the page.


10. Type a color name such as "red" or "blue" in the text box, and then click Change Color.
ASP.NET caches a version of the page that uses the color you specify.
11. Refresh the page a number of times.
If you do not type in a new color name, the date and time will not change for at least one minute, as specified by the
Duration attribute in your @ OutputCache directive.
12. Enter a new color, such as "green" or "orchid" and then submit the page.
This time you will see the time update along with the new color.
Next Steps
This walkthrough has illustrated basic concepts of caching ASP.NET pages. You might also want to explore these additional
caching techniques:
Instead of using page declarations, specify caching programmatically. For example, in your Page_Load method you could
access the HttpCachePolicy class (through Page.Response.Cache), and set values and behavior accordingly.
Cache data-bound pages so that they are regenerated only when the data they are dependent on has changed. For
details, see Walkthrough: Using ASP.NET Output Caching with SQL Server.
See Also
Tasks
Walkthrough: Using ASP.NET Output Caching with SQL Server
Reference
@ OutputCache
HttpCachePolicy
VaryByParams
Concepts
ASP.NET Caching Overview
Visual Web Developer

Walkthrough: Using ASP.NET Output Caching with SQL Server


This walkthrough shows how to cache ASP.NET pages that depend on data in a SQL Server database.
An advanced feature of ASP.NET output caching is SQL cache dependency. SQL cache dependency enables you to cache pages
that are dependent on data from SQL Server tables. You can configure SQL Server and ASP.NET to cache page requests,
reducing server workload, until the data on which the page depends has been updated in SQL Server. SQL cache dependency
is useful for data such as product catalogs or customer registration information that remains comparatively static.
Tasks illustrated in this walkthrough include:
Creating and configuring a page to display data from the Northwind database.
Enabling a database for SQL cache notification.
Specifying the SQL cache dependency on your page and in your Web.config file.
Making changes to the Northwind database and viewing the caching behavior.
Prerequisites
In order to complete this walkthrough, you will need:
Access to SQL Server 2000 or SQL Server 2005 with the Northwind database.
Access to the SQL Server Northwind database. For information about downloading and installing the SQL Server sample
Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site.
Note
If you need information about how to log on to the computer running SQL Server, contact the server administrator.

Microsoft Data Access Components (MDAC) version 2.7 or later.


If you are using Windows XP or Windows Server 2003, you already have MDAC 2.7. However, if you are using Windows
2000, you might to need to upgrade the MDAC already installed on your computer. For more information, see the MSDN
article MDAC Installation.
The .NET Framework version 2.0.
Creating the Web Site
If you have already created a Web site in Visual Web Developer (see
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and go to "Enabling Cache
Notification for SQL Server" later in this walkthrough. Otherwise, create a new Web site and page using the following
procedure.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site. (In Visual Web Developer Express Edition, on the File menu click New, and then
click Web Site.)
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of your Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Enabling Cache Notification for SQL Server
You must configure SQL Server to provide proper notification to ASP.NET regarding changes in dependent data. You will need
administrative privileges to configure the server.
To enable cache notification for SQL Server
1. On the Windows Start menu, point to All Programs, point to Accessories, and then click Command Prompt to open a
command prompt window.
2. Locate the Aspnet_regsql.exe executable file on your disk drive. This file is installed with the .NET Framework version 2.0
in the following location:

%windir%\Microsoft.NET\Framework\FrameworkVersion

Be sure that %windir% represents your Windows directory and that the .NET Framework version is 2.0 or later. The path
might look like the following:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.40217

3. Use the following command to enable cache notification for the Employees table in the Northwind database:

aspnet_regsql.exe -S <Server> -U <Username> -P <Password> -ed -d Northwind -et -t Empl


oyees

Note
You will need administrative privileges or the administrative account and password. If you do not have this information
, contact your database administrator.

A message will appear indicating success or failure in enabling the database. The following message indicates success:

Enabling the table for SQL cache dependency.


..
Finished.

Adding a Data Connection to the Project


To work with the SQL Server database in Visual Web Developer, you need to add a connection to the Northwind database.
To add a data source to the project
1. In Server Explorer (Database Explorer in Visual Web Developer Express Edition), right-click Data Connections, and
then click Add Connection.
Note
Server Explorer (Database Explorer in Visual Web Developer Express Edition) is typically docked behind Solution Ex
plorer.

If Server Explorer (Database Explorer in Visual Web Developer Express Edition) is not visible, in the View menu, click
Server Explorer (Database Explorer in Visual Web Developer Express Edition).
2. If the Choose Data Source dialog box is displayed, do the following:
a. In the Data source list, click Microsoft SQL Server.
b. In the Data provider list, click .NET Framework Data Provider for SQL Server.
c. Click Continue.
3. In the Add Connection dialog box, provide the details (server name, login credentials, and so on) for your database, and
then select the Northwind database.
4. Click OK.
Adding a Time Stamp and Data to the Web Page
You can now create a Web page to demonstrate caching. In this section you will add a time stamp to track page creation times
and a GridView control to view the Employees table of the Northwind database.
To add a time stamp and data to the Web page
1. Switch to or open the Default.aspx page.
2. Switch to Design view.
3. From the Standard group in the Toolbox, drag a Label control onto the page, leaving the default name of Label1.
4. In Server Explorer (Database Explorer in Visual Web Developer Express Edition), expand Data Connections.
5. Expand the node for the data connection you created earlier.
6. Expand the Tables node.
7. Drag the Employees table to your page.
Visual Web Designer creates a GridView control that is configured to use the connection and table you selected.
8. In the GridView Tasks menu, click Configure Data Source.
The default data connection string name NorthwindConnectionString1 appears in the first step of the Configure Data
Source wizard.
9. Click Next.
10. In the Configure Select Statement pane, select Specify columns from a table or view.
11. In the Name list, click Employees.
12. In the Columns list, select the EmployeeID, LastName, and FirstName columns.
13. Click Next.
14. Click Finish.
Visual Web Designer configures the GridView control to display the data you have selected.
Note
If you see a message asking whether you want to refresh the fields and keys for the GridView control, click Yes.

15. Double-click a blank part of the page.


The designer generates a Page_Load method and switches views.
16. Add the following highlighted code to display a time stamp indicating page creation:
VB
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles Me.Load
Label1.Text = System.DateTime.Now
End Sub

C#
protected void Page_Load(Object sender, System.EventArgs e)
{
Label1.Text = System.DateTime.Now.ToString();
}

17. Save the file.


Testing the Page without Caching
Now you can run the page and observe the behavior without caching. The page is loaded and the current server time is
displayed, and then the data is retrieved and placed on the page.
To test the page without caching
1. Press CTRL+F5 to run the page.
2. Refresh the page in the browser
Note that the time stamp changes with each page refresh. The data remains the same.
Configuring the Web Page for Caching
In this part of the walkthrough, you will configure the page for SQL cache dependency based on the Employees table of the
Northwind database.
To configure the Web page for caching
1. Switch to Source view.
2. At the top of the page, add the following directive to indicate the dependency:

<%@ OutputCache Duration="3600" SqlDependency="Northwind:Employees" VaryByParam="none"


%>

The VaryByParam attribute indicates whether ASP.NET should take into consideration page parameters (such as query string
or posted values) when caching. When VaryByParam is set to none, no parameters will be considered; all users are sent the
same page no matter what additional parameters are supplied. Setting VaryByParam to * (an asterisk) means that for each
unique combination of request parameters a unique page will be cached. However, setting VaryByParam to * can cause many
different versions of the page to be cached, so if you know the parameters to vary caching by, it is recommended that you
explicitly specify them in the VaryByParam attribute. For details, see Caching Multiple Versions of a Page.
Setting Caching Configuration in the Web.config File
In addition to the OutputCache declaration on your Web page in the preceding section, you need to specify caching details in
the Web.config file.
To create and update the Web.config file
1. If your Web site already has a Web.config file, go to step 4.
2. In Solution Explorer, right-click the name of your Web site and then click Add New Item.
3. In the Add Item dialog box, click Web Configuration File, and then click Add.
Be sure to use the name Web.config.
4. Add the following XML to the Web.config file as a child of the system.web element:

<!-- caching section group -->


<caching>
<sqlCacheDependency enabled = "true" pollTime = "1000" >
<databases>
<add name="Northwind"
connectionStringName="NorthwindConnectionString1"
pollTime = "1000"
/>
</databases>
</sqlCacheDependency>
</caching>

Note
The connection string name NorthwindConnectionString1 was established earlier when you created the data conne
ction. If your connection string has a different name, substitute that name instead.

Note
The account credentials specified in the connection string must have sufficient privileges to poll the database.

5. Save the file and then close it.


Testing the Page with Caching
With caching enabled, refreshing the page will no longer result in an updated time stamp or a database query, because
ASP.NET will fulfill the page request from the cache.
To test the page with caching
Press CTRL+F5 to run the page.
Note that the time stamp remains the same with each page refresh. The page is being retrieved from the cache.
Changing the Data
Now you can change the data in the database and see that the cache is invalidated and a new page is created.
To change the data
1. In Server Explorer (Data Explorer in Visual Web Developer Express Edition), expand the Data Connections node.
2. Expand the connection you created earlier.
3. Expand the Tables node.
4. Right-click Employees, and then click Show Table Data.
5. Update the database by editing any field in the data table, ensuring it is a field your Web page is displaying.
Alternatively, you can use the SQL pane (if the SQL pane is not visible, in the Query Designer menu, click Pane, and
then click SQL). Enter a SQL command directly and then click the Execute SQL button in the Query Designer toolbar. For
example, run the following command:

UPDATE dbo.Employees SET LastName = 'Doe' WHERE (EmployeeID = 5)

This changes the name of employee 5 to Doe.


6. Close the view of the data.
Testing the SQL Cache Dependency
You can now test the page to see whether the data and timestamp have changed.
To test SQL cache dependency
1. Press CTRL+F5 to run the page.
Note that the time stamp has changed and that the new data is displayed.
2. Press CTRL+F5 to run the page again.
This time the time stamp remains the same, because the data has not changed, and the page is now being retrieved once
again from the cache.
Next Steps
You can cache pages using other parameters as well. For information, see
Walkthrough: Using Output Caching to Enhance Web Site Performance. If you are not familiar with data access, see
Walkthrough: Basic Data Access in Web Pages.
See Also
Reference
DefaultHttpCachePolicy
OutputCacheSettingsSection
Concepts
Caching in ASP.NET with the SqlCacheDependency Class
Visual Web Developer

Additional Page Techniques


The topics in this section include step-by-step walkthroughs that illustrate how to create reusable elements by using user
controls, HTML tables, master pages, Web parts, and the Wizard control.
In This Section
Walkthrough: Creating Reusable Elements with ASP.NET User Controls
Walkthrough: Editing HTML Tables in Visual Web Developer
Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer
Walkthrough: Creating a Basic ASP.NET Wizard Control
Walkthrough: Creating a Web Parts Page in Visual Web Developer
Related Sections
Guided Tour of Creating Web Sites in Visual Web Developer
Contains topics that give an introductory guided tour of the process of creating Web sites in Visual Web Developer.
Visual Web Developer

Walkthrough: Creating Reusable Elements with ASP.NET User


Controls
ASP.NET user controls let you encapsulate the functionality of multiple server controls in a unit. User controls are made up of
one or more ASP.NET server controls—Button controls, TextBox controls, and so on—along with any code that is required for
the controls to perform the function that you want to accomplish. The user control can also include custom properties or
methods that reveal the functionality of the user control to a container, which is typically an ASP.NET page.
In this walkthrough, you will create an ASP.NET user control that acts as a picker control. The picker control has two lists, with a
set of choices in one list (the source). Users can select items in the SourceList list, and then add the items to the TargetList list.
This walkthrough has three parts, as follows:
In the first part, you will create the basic user control, adding controls and code.
In the second part, you will create a new ASP.NET page (the host page), and then add the user control to the ASP.NET
page.
In the third part, you will add custom properties and methods to the user control so that you can interact with the control
from the host page.
Tasks illustrated in this walkthrough include the following:
Creating a user control and adding ASP.NET server controls to the user control.
Creating properties and a method in the user control.
Adding a user control to a host page.
Adding code to the host page to handle the user control.
Prerequisites
In order to complete this walkthrough, you will need the following:
The Microsoft Visual Web Developer Web development tool.
The Microsoft .NET Framework.
This walkthrough assumes that you have a general understanding of working in Visual Web Developer. For an introduction,
see Walkthrough: Creating a Basic Web Page in Visual Web Developer.
Creating the Web Site
If you have already created a Web site in Visual Web Developer (for example, by completing
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and go to the next section.
Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, point to New, and then click Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the right-most Location box, enter the name of the folder where you want to keep the pages of the Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language that you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating the User Control
Creating a user control is similar to creating an ASP.NET Web page. In fact, a user control is effectively a subset of an ASP.NET
page and it can include most of the types of elements that you put on an ASP.NET page.
To create a user control
1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
2. In the Add New Item <Path> dialog box, under Visual Studio installed templates, click Web User Control.
3. In the Name box, type ListPicker.
The user control file will have an .ascx extension, which is added automatically to ListPicker.
4. In the Language list, select the programming language that you prefer to work in.
5. Click Add.
The new control is created and is opened in the designer. The markup for the control looks similar to that for a page, with
one important exception: there is no @ Page directive at the top of the page. Instead, there is an @ Control directive,
which identifies the file to ASP.NET as a user control.
Adding Server Controls to the User Control
In this part of the walkthrough, you will add the controls that make up the user interface for the user control.
To add server controls
1. Switch to Design view.
2. On the Layout menu, click Insert Table.
3. Use the Insert Table dialog box to create a table with one row and three columns, and then click OK.
You are creating the table to hold the controls; that is, a layout table.
4. In the table, in the left column, type Available, and then press ENTER to create a new line.
5. In the right column, type Selected, and then press ENTER to create a new line.
6. from the Standard group in the Toolbox, drag the following controls onto the table and set their properties as indicated.
Control Properties
Drag a ListBox to the left column and place it under Available. Height: 200px
ID: SourceList
Width: 200px

Drag a Button to the middle column. ID: AddAll


Text: >>

Drag a Button to the middle column. ID: AddOne


Text: (SPACEBAR)>( SPACEBAR)

Drag a Button to the middle column. ID: Remove


Text: (SPACEBAR)X(SPACEBAR)

Drag a ListBox to the right column and place it under Selected. Height: 200px
ID: TargetList
Width: 200px

ImageButton controls can be used instead of Button controls so that an image is displayed that responds to mouse clicks.
However, for this walkthrough, it is sufficient to use text that emulates the type of graphic that is frequently used to
indicate Add All, Add, and Remove, which are the two right angle brackets (>>), one right angle bracket (>), and the X,
respectively.
7. If you want, adjust the width and height of the table columns to your preference.
8. Click the SourceList list, and then in Properties, for the Items property, click the ellipsis (…) button.
The ListItem Collection Editor dialog box appears.
9. Click Add three times to add three items
10. For the first, second, and third item, under ListItem properties, set Text to A, B, and C, respectively.
You are creating test data for now. Later in this walkthrough, in "Adding Custom Properties and Methods to the User
Control," you will remove the test data and add code to load the SourceList list dynamically.
Adding Code to Handle User Selections
Users will select items using the buttons that are in the middle column of the table. Therefore, most of the code for the control
is in handlers for the Click events.
To add code to handle user selections
1. In Design view, double-click the >> (AddAll) button to create an event handler for the Click event, and then add the
following highlighted code.
VB
Protected Sub AddAll_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles AddAll.Click
TargetList.SelectedIndex = -1
Dim li As ListItem
For Each li In SourceList.Items
AddItem(li)
Next
End Sub

C#
protected void AddAll_Click(object sender, EventArgs e)
{
TargetList.SelectedIndex = -1;
foreach(ListItem li in SourceList.Items)
{
AddItem(li);
}
}

The code loops through all the list items in the SourceList list. For each item, it calls the AddItem method and passes it
the current item. Later in this procedure, you will write the code for the AddItem method.
2. Switch to Design view, double-click the > (AddOne) button to create an event handler for the Click event, and then add
the following highlighted code:
VB
Protected Sub AddOne_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles AddOne.Click
If SourceList.SelectedIndex >= 0 Then
AddItem(SourceList.SelectedItem)
End If
End Sub
C#
protected void AddOne_Click(object sender, EventArgs e)
{
if(SourceList.SelectedIndex >= 0)
{
AddItem(SourceList.SelectedItem);
}
}

This code first checks that there is a selection in the SourceList list. If there is, the code calls the AddItem method, which
you will write later in this procedure, passing it the item that is currently selected in the SourceList list.
3. Switch to Design view, double-click the X (Remove) button to create an event handler for the Click event, and then add
the following highlighted code:
VB
Protected Sub Remove_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles Remove.Click
If TargetList.SelectedIndex >= 0 Then
TargetList.Items.RemoveAt(TargetList.SelectedIndex)
TargetList.SelectedIndex = -1
End If
End Sub

C#
protected void Remove_Click(object sender, EventArgs e)
{
if(TargetList.SelectedIndex >= 0)
{
TargetList.Items.RemoveAt(TargetList.SelectedIndex);
TargetList.SelectedIndex = -1;
}
}

The code first checks that the TargetList list contains a selection. If there is a selection, the code removes the selected
item from the list and the selection.
4. Add the following AddItem method:
VB
Protected Sub AddItem(ByVal li As ListItem)
TargetList.SelectedIndex = -1
TargetList.Items.Add(li)
End Sub

C#
protected void AddItem(ListItem li)
{
TargetList.SelectedIndex = -1;
TargetList.Items.Add(li);
}

This code unconditionally adds an item to the TargetList list. Later in this walkthrough, in "Adding Custom Properties
and Methods to the User Control," you will improve this code by adding the option to determine whether there are
duplicates.
You cannot directly test a user control, because it must be hosted in a page. In the next section, you will create an ASP.NET Web
page where you can work with the control.
Using the User Control
Like any control, a user control must be hosted in a page. In this part of the walkthrough, you will create a host page for the
control, and then you will add a user control to the page.
To create a host page
1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
2. Under Visual Studio installed templates, click Web Form.
3. In the Name box, type HostUserControl.
4. In the Language list, select the language that you prefer to work in, and then click Add.
The new page appears in the designer.

To add the user control to the page


1. Switch to Design view.
2. From Solution Explorer, drag the user control file (ListPicker.ascx) onto the page.
Note
Be sure that you are in Design view when you drag ListPicker.ascx onto the page.

The control appears in the designer.


3. Switch to Source view.
Placing the user control on the page creates two new elements in the page:
At the top of the page is a new @ Register directive and it looks similar to the following:

<%@ Register Src="ListPicker.ascx" TagName="ListPicker"


TagPrefix="uc1" %>

The @ Register directive is required, because the user control is an external component. The values that are in the
directive provide information that is required by ASP.NET to find the control when compiling and running the page.
Together, the TagPrefix and TagName attributes specify how the user control is declared on the page. The Src
attribute specifies the file, and if it is necessary, the path, where the source file is located.
The second new element is the element for the user control and it looks similar to the following:

<uc1:ListPicker id="ListPicker1" Runat="server" />

The element for a user control looks similar to the element for an ordinary ASP.NET server control. The difference is
that the user control has a different tag prefix (uc1) and a unique tag name (ListPicker). Although the values were
established automatically by the @ Register directive when you placed the user control on the page, you can use
any tag prefix and tag name for your user control, as long as the values are not already being used in the page.
Testing the User Control
Now, you can test the preliminary version of the user control.
To test the user control
1. Press CTRL+F5 to run the page.
The page appears in the browser and you can see the two lists and three buttons that make up your user control.
2. Click the >> (AddAll) button.
All values from the SourceList list are copied to the TargetList list.
3. Click each item in the TargetList list in turn, and then click the X (Remove) button until you have removed all items.
4. Select a single value in the SourceList list, and then click the > (AddOne) button.
The single value is copied to the TargetList list.
5. Optionally, experiment more with the control until you are sure that it works as you intend it to.
6. When you are finished, close the browser.
Adding Custom Properties and Methods to the User Control
Your user control now works, but it is not yet useful as a general-purpose control. A more practical version of the user control
would let you do the following:
Specify the list of items to display in the SourceList list dynamically.
Get the list of items that the user selected in the TargetList list.
Specify whether you want to allow duplicate values in the TargetList list, optionally.
Provide a way for users to clear all items in the TargetList list quickly.
Performing these tasks requires that the host page can communicate with the user control, both to share values (set and read
properties) and to issue commands (call methods). In this part of the walkthrough, you will change the user control and add
some members (properties and methods) to it.
You will add two properties to the user control. The first property retrieves the list of items that are in the TargetList list. The
second property lets you specify whether the TargetList list accepts duplicate values. Later in this section, you will add a
method that will let you populate the SourceList list.
To add code to define custom properties
1. For the ListPicker control, open or switch to the code file.
2. Use the following code to create the SelectedItems property:
VB
Public ReadOnly Property SelectedItems() As ListItemCollection
Get
Return TargetList.Items
End Get
End Property

C#
public ListItemCollection SelectedItems
{
get { return TargetList.Items ; }
}

The SelectedItems property retrieves the values that are in the TargetList list. It can be read-only, because you will
never have to set the values in the TargetList list programmatically.
3. Use the following code to create the AllowDuplicates property:
VB
Public Property AllowDuplicates() As Boolean
Get
Return CType(ViewState("allowDuplicates"), Boolean)
End Get
Set(ByVal value As Boolean)
ViewState("allowDuplicates") = value
End Set
End Property

C#
public Boolean AllowDuplicates
{
get
{
return (Boolean)ViewState["allowDuplicates"];
}
set
{
ViewState["allowDuplicates"] = value;
}
}

The AllowDuplicates property is a read/write property. The value of the AllowDuplicates property must be saved
explicitly in View state so that it persists between round trips. (The SelectedItems property does not have to be explicitly
saved in View state, because the TargetList list saves the values in View state.)
You now have the properties defined. However, you still must modify the existing code in the user control to take advantage of
the AllowDuplicates property setting.
To modify existing code to use the AllowDuplicates property
Find the AddItem method that you wrote in "Adding Code to Handle User Selections," earlier in this walkthrough, and
replace the contents with the following highlighted code:
VB
Protected Sub AddItem(ByVal li As ListItem)
TargetList.Selectedindex = -1
If Me.AllowDuplicates = True Then
TargetList.Items.Add(li)
Else
If TargetList.Items.FindByText(li.Text) Is Nothing Then
TargetList.Items.Add(li)
End If
End If
End Sub

C#
protected void AddItem(ListItem li)
{
TargetList.SelectedIndex = -1;
if(this.AllowDuplicates == true)
{
TargetList.Items.Add(li);
}
else
{
if(TargetList.Items.FindByText(li.Text) == null)
{
TargetList.Items.Add(li);
}
}
}

The code performs the same function as before (adding an item to the TargetList list), but now the code checks to
determine whether the AllowDuplicate property is set to true. If the AllowDuplicate property is set to true, the code
first looks for an existing item with the same value as the proposed new item, and then adds the new item, but only if no
existing item is found.
Because you will be setting the contents of the SourceList list using a property, you can remove the test data that you entered
in "Adding Server Controls to the User Control," earlier in this walkthrough.
To remove the test data for the SourceList list
1. Switch to Design view.
2. Click the SourceList control, and then, in Properties, for Items, click the ellipsis (…) button.
The ListItem Collection Editor appears.
3. Click the X (Remove) button to remove each sample item, and then click OK.
Adding a Method to the User Control
You can also add methods to perform tasks in the user control when the methods are called by code in the host page. To
illustrate this, in this walkthrough, you will add two methods. The first method can be called to add items to the SourceList list.
The second method clears the contents of the TargetList list.
To add a method to clear the TargetList list
1. Use the following code to add the AddSourceItem method:
VB
Public Sub AddSourceItem(ByVal sourceItem As String)
SourceList.Items.Add(sourceItem)
End Sub

C#
public void AddSourceItem(String sourceItem)
{
SourceList.Items.Add(sourceItem);
}

2. Use the following code to add the ClearAll method:


VB
Public Sub ClearAll()
SourceList.Items.Clear()
TargetList.Items.Clear()
End Sub

C#
public void ClearAll()
{
SourceList.Items.Clear();
TargetList.Items.Clear();
}

3. On the File menu, click Save All to save the changes that you made to the user control.
Testing the User Control Properties and Method
The final task in this walkthrough is to enhance the host page to be able to share values with the user control. You can set
some of the properties for the user control declaratively. (You cannot set the SourceList list directly using the code in this
walkthrough, but you can set it programmatically.) In this procedure, you will set the AllowDuplicates property to a default
value of true.
To set user control properties declaratively
1. Switch to or open the HostUserControl.aspx page.
2. In Source view, set AllowDuplicates declaratively by using syntax that it similar to the following:

<uc1:ListPicker id="ListPicker1" Runat="server"


AllowDuplicates="true" />

Notice that you obtain Microsoft IntelliSense functionality for AllowDuplicates.


Working with the User Control Programmatically
You can also work with the user control programmatically, setting and retrieving the properties and calling the methods. To
illustrate how to work with the user control programmatically, you will add some controls to the host page.
To work with the user control programmatically
1. Switch to Design view.
2. From the Standard group in the Toolbox, drag the following controls onto the table on the host page, and then set the
properties as indicated.
Control Properties
TextBox ID: NewItem
Text: (empty)

Button ID: AddItem


Text: Add Item

Button ID: LoadFiles


Text: File List

Button ID: ClearSelection


Text: Clear All

CheckBox AutoPostBack: True


Checked: True
ID: AllowDuplicates
Text: Allow duplicates

Button ID: ShowSelection


Text: Show Selection

Label ID: Selection


Text: (empty)

3. In Design view, double-click AllowDuplicates to create an event handler for the CheckedChanged event, and then add
the following highlighted code:
VB
Protected Sub AllowDuplicates_CheckedChanged( _
ByVal sender As Object, _
ByVal e As EventArgs) Handles AllowDuplicates.CheckedChanged
ListPicker1.AllowDuplicates = AllowDuplicates.Checked
End Sub

C#
protected void AllowDuplicates_CheckedChanged(Object sender, EventArgs e)
{
ListPicker1.AllowDuplicates = AllowDuplicates.Checked;
}

4. Switch to Design view, double-click AddItem to create an event handler for the Click event, and then add the following
highlighted code:
VB
Protected Sub AddItem_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles AddItem.Click
Dim sourceItem As String = Server.HtmlEncode(NewItem.Text)
ListPicker1.AddSourceItem(sourceItem)
End Sub

C#
protected void AddItem_Click(object sender, EventArgs e)
{
ListPicker1.AddSourceItem(Server.HtmlEncode(NewItem.Text));
}

The code creates a ListItemCollection collection in code and populates it with sample data. Then, the code sets the
SourceItems property to the collection.

5. Switch to Design view, double-click LoadFiles to create an event handler for the Click event, and then add the following
highlighted code:
VB
Protected Sub LoadFiles_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles LoadFiles.Click
Dim path As String = Server.MapPath(Request.ApplicationPath)
Dim files() As String = System.IO.Directory.GetFiles(path)
Dim filename As String
For Each filename in Files
ListPicker1.AddSourceItem(filename)
Next
End Sub

C#
protected void LoadFiles_Click(object sender, EventArgs e)
{
String path = Server.MapPath(Request.ApplicationPath);
String[] files = System.IO.Directory.GetFiles(path);
foreach(String filename in files)
{
ListPicker1.AddSourceItem(filename);
}
}
This code is similar to the code for AddItem, except that this code adds a list of files in the Web site root directory.
6. Switch to Design view, double-click ShowSelection to create an event handler for the Click event, and then add the
following highlighted code:
VB
Protected Sub ShowSelection_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles ShowSelection.Click
Dim lItem As ListItem
Dim selectedItemsString As String = ""
For Each lItem in ListPicker1.SelectedItems
selectedItemsString &= "<br>" & lItem.Text
Next
Selection.Text = selectedItemsString
End Sub

C#
protected void ShowSelection_Click(object sender, EventArgs e)
{
String selectedItemsString = "";
foreach(ListItem lItem in ListPicker1.SelectedItems)
{
selectedItemsString += "<br>" + lItem.Text;
}
Selection.Text = selectedItemsString;
}

This code retrieves an object that is typed as a ListItemCollection object, reads each item in the collection, and then
displays the results in Selection.
7. Switch to Design view, double-click ClearSelection to create an event handler for the Click event, and then add the
following highlighted code:
VB
Protected Sub ClearSelection_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles ClearSelection.Click
ListPicker1.ClearAll()
End Sub

C#
protected void ClearSelection_Click(object sender, EventArgs e)
{
ListPicker1.ClearAll();
}

This code invokes the ClearAll method for the user control to remove all items from the TargetList.
Testing the Finished User Controls
Now, you can test your finished user control.
To test the user control
1. Press CTRL+F5 to run the page.
2. In the text box, type a value, and then click Add Item.
3. Repeat step 2 several times, until you have a selection of items in the user control.
4. Use the buttons to select one or more of the source items from the SourceList list, and then add them to the TargetList
list.
5. Click Show Selection.
The TargetList list items are displayed in Selection.
6. Click Clear All.
7. Click File List.
The SourceList list now displays a list of file names.
8. In the user control, click Add to add several items to the TargetList list.
9. Try adding an item to the TargetList list that is already in the list.
The duplicate value is added.
10. Clear the Allow duplicates box, and then try adding duplicates again.
This time, the duplicates are not added to the TargetList list.
11. Click Show Selection.
The list of items in the TargetList list is displayed in the host page.
Next Steps
Although the control that you have created is not very complex, you have seen much of the basic functionality that you can
build into a user control. Refining the control is largely a matter of revealing additional properties and methods that enhance
what you can do with the control. Additional members might include the following:
Appearance properties.
You can create user control properties that let a user set the background, list size, and so on, for the control.
Note
By default, the user control uses the current theme that applies to the child controls. For example, if you have a skin defi
ned for a Button control, the buttons in your user control are displayed with that skin.

Data properties.
You can add properties that enable the user control to use a wider variety of data to display in the SourceList list. For
example, you could add properties to set a dataset, data table, and data display field.
Functionality.
You can add more buttons and code to the user control to enable users not just to copy items from the SourceList list to
the TargetList list, but also to move items—where the item is removed from the SourceList list as it is moved to the
TargetList list. The control could then have buttons that could move the data back from the TargetList list to the
SourceList list.
See Also
Tasks
How to: Convert Web Forms Pages into ASP.NET User Controls
Concepts
ASP.NET User Controls Overview
Web Application Security Threats Overview (Visual Studio)
Visual Web Developer

Walkthrough: Editing HTML Tables in Visual Web Developer


Table editing is an important part of many Web pages because tables are used to create the page layout. This walkthrough
illustrates the table-editing features of the HTML editor in Microsoft Visual Studio. You will use tables to create the layout for a
simple entry form on the page.
Note
The table-editing features described in this walkthrough pertain to HTML tables, not to the Table Web server control (the <as
p:Table> control and its child controls).

Tasks illustrated in this walkthrough include:


Adding a table.
Selecting the table, rows, and columns.
Resizing elements.
Adding and removing table elements.
Setting cell characteristics such as background color and alignment.
Prerequisites
In order to complete this walkthrough, you will need:
Visual Web Developer and the .NET Framework.
Creating the Web Site
If you have already created a Web site in Visual Studio (for example, by following the steps in
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and skip to the next section,
"Creating the Page Layout with a Table." Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of your Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating the Page Layout with a Table
You will begin by adding a table that defines the overall layout of the page.
To add a table for the page layout
1. If you do not already have a page open in the designer, add a page to the Web site.
2. Switch to Design view.
3. In the Layout menu, click Insert Table.
The Insert Table dialog box appears.
4. Select Template.
Table templates are predefined table layouts.
5. In the Template list, select Header and side.
6. Click OK.
A two-column table is added to the page that takes up the entire height and width of the page. A single cell on top spans
the columns, providing a place to put a header. The left-hand cell below the header is for navigation or side information.
The right-hand cell below the header is the main display area for the page.
Note
The borders around the cells in the table are displayed by default at design time to help you edit. Unless you explicitly s
et the table or cells to have a border, no border will appear when the table is rendered in the browser.

Creating a Form Layout with a Table


You can also use HTML tables to lay out the controls in a form. You will now create a second table inside the first one. You will
later use the second table to create the layout for some controls in a form.
To add a table for the form layout
1. From the HTML group of the Toolbox, drag a Table element into the right-hand (main) cell.
When you drag a table from the Toolbox, Visual Web Developer creates an empty table of three columns and three
rows. You need only two columns; in a moment, you will delete one of the columns.
Note
You can create tables either by using the Insert Table command, as you did earlier, or by dragging a Table element fr
om the Toolbox.

2. Move the mouse pointer over the table until the pointer changes to a move cursor (four-headed arrow), and then click to
select the table.
3. Drag the right-hand edge of the table to widen the table until it is most of the width of the page.
As you drag, the table displays its current dimensions.
4. Right-click in one of the cells in the left-most column. From the Delete sub-menu, click Columns to remove the column
of the selected cell.
The column is deleted from the table.
Note
If you see a Delete option that does not have a submenu, it indicates that the focus is not in a cell. Right-click inside a c
ell in the left-hand column.

5. Click in the bottom right-hand cell and then press the TAB key to add a fourth row to the table.
You now have a table of two columns and four rows, which can be the container for your form controls.
Setting Characteristics of the Page Layout Table
Now that you have a form layout table inside the page table, you can finish laying out the page by editing the page layout
table.
To set characteristics of the page layout table
1. In the page layout table, click in the top cell.
The thicker border around the cell indicates that it is selected and in content-edit mode.
2. In the Properties window, click the button in the Style box.
The Style Builder dialog box appears.
3. On the Text tab, in the Horizontal list, click Centered.
4. On the Background tab, in the Color list, select a color you like. You can also click the button next to the Color box to
display the Color Picker dialog box and select from additional colors.
The settings you have made set the style for the cell at the top of the layout table.
5. Type Contoso Web Site as a heading.
6. Select the text and, in the Block Format list in the Formatting toolbar, click Heading 1 <H1>.
7. Repeat steps 1 through 6 for the leftmost cell in the table, with these changes:
Change the text to This site is maintained by Contoso, Incorporated.
Do not format the text as a Heading 1.
In the Text tab of the Style Builder dialog box, in the Vertical list, click bottom.
In a production Web page, the side cell would probably be occupied by a menu of links or other content. However, for
this walkthrough it does not matter what content the cell contains.
Building the Form
You can now build the form.
To add text and controls to the form layout table
1. In the form layout table (the table inside the page layout table), click in the top left cell and type Name:.
2. Click in the left cell of the second row and type Birth year:.
3. From the Standard group of the Toolbox, drag a TextBox control into the top right cell.
4. Set the TextBox control's ID property to textName.
5. Drag another TextBox into the second row's right cell and set its ID property to textBirthYear.
6. Drag a Button control into the third cell on the right and set its Text property to Submit.
7. Drag a Label control into the bottom right cell, set its ID property to labelDisplay, and clear its Text property.
8. Place the mouse cursor over the left-hand column until you see a selection symbol (a small square) at the top of the
column, and then click the symbol.
The left column is selected.
9. In the Properties window, click the button in the Style box to display the Style Builder dialog box.
10. In the Text tab, in the Horizontal list, click Right.
The text captions in the form are right-aligned.
11. Click OK to close the style builder.
12. Select the left column again, and then drag its right edge to shrink the column until it is just wide enough to fit the
caption text.
13. Right-click in the layout table cell outside the form layout table, and then click Style.
The shortcut menu provides an alternate way to display the Style Builder dialog box.
14. In the Text tab, in the Vertical list, click top.
The form layout table is aligned at the top of the cell.
Programming the Form Controls
You can now program the form controls. The form displays the age that the user will be this year.
To program the form controls
1. Double-click the Button control in the form.
The editor creates a Click event handler.
2. Add the following highlighted code.
VB
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Dim age As Integer
age = DateTime.Now.Year - CInt(textBirthYear.Text)
labelDisplay.Text = Server.HtmlEncode(textName.Text) & _
", this year you are " & Server.HtmlEncode(age.ToString())
End Sub

C#
protected void Button1_Click(Object sender, EventArgs e)
{
int age = DateTime.Now.Year - Int32.Parse(textBirthYear.Text);
labelDisplay.Text = Server.HtmlEncode(textName.Text) +
", this year you are " + Server.HtmlEncode(age.ToString());
}

Testing the Page


You can now test the page.
To test the page
1. Press CTRL+F5 to run the page.
When the page is displayed in the browser, note the layout that you have created. Because you did not explicitly specify
table borders, there are no lines on the form.
2. In the Name box, type your name.
3. In the Birth year box, type the year you were born, and then click the Submit button.
The age calculation is displayed in the form in the location you created with the form table.
Next Steps
In this walkthrough, you have exercised some of the capabilities of the visual table editor in Design view. You added tables in
two ways, resized a table, added a row, deleted a column, set cell styles, and added text and controls as cell contents.
Suggestions for more exploration include:
Learn more ways to work with tables. For details, see:
How to: Add and Remove HTML Table Elements in Visual Web Developer
How to: Select HTML Table Elements and Contents in Visual Web Developer
How to: Resize HTML Table Elements in Visual Web Developer
Learn some tips for editing tables in both Design view and Source view. For details, see
HTML Table Editing Tips in Visual Web Developer.
Add validation to the Birth year text box so that users can enter only valid years. For more information, see
Validating User Input in ASP.NET Web Pages.
See Also
Tasks
Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer
Concepts
HTML Editor Tag Navigation in Visual Web Developer
Formatting Elements in the HTML Editor in Visual Web Developer
Visual Web Developer

Walkthrough: Creating and Using ASP.NET Master Pages in


Visual Web Developer
This walkthrough illustrates how to create a master page and several content pages. Master pages allow you to create a page
layout — a template page — and then create separate pages containing content that is merged with the master page at run
time. For more information about master pages, see ASP.NET Master Pages Overview.
Tasks illustrated in this walkthrough include:
Creating a master page in Microsoft Visual Web Developer.
Creating an ASP.NET page with content that you want to display in the master page.
Running master pages to show different content.
Selecting a master page at run time.
Prerequisites
In order to complete this walkthrough, you will need:
Visual Web Developer (Visual Studio).
The .NET Framework.
Optionally, a .jpg, .gif, or other graphics file that you can use as a logo on your master page. It is recommended that the
logo be no more than 48 pixels wide. However, displaying a logo is optional and the graphic's exact size is not critical to
the walkthrough.
Creating a Web Site
If you have already created a Web site in Visual Web Developer (for example, by following the steps in
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and skip to the next section,
"Creating the Master Page." Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of your Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating the Master Page
The master page is the template for how your pages will look. In this section, you will first create a master page. You will then
use a table to lay out the master page with a menu, a logo, and a footer that will appear on each page of your site. You will also
work with a content placeholder, which is a region in the master page that can be replaced with information in a content page.
To create the master page
1. In Solution Explorer, right-click the name of your Web site, and then click Add New Item.
2. Under Visual Studio installed templates, click Master Page.
3. In the Name box, type Master1.
4. Select the Place code in separate file check box.
Note
This walkthrough assumes you are using code-behind files for all pages. If you are using a single-file ASP.NET page, the
code illustrated in this walkthrough will work, but will appear in Source view, not in a separate code file.

5. In the Language list, click the programming language you prefer and then click Add.
The new master page opens in Source view.
At the top of the page is an @ Master declaration instead of the @ Page declaration normally found at the top of ASP.NET
pages. The body of the page contains an <asp:contentplaceholder> control, which is the area of the master page
where replaceable content will be merged from content pages at run time. You will work more with the content
placeholder later in this walkthrough.
Laying Out the Master Page
The master page defines how the pages in your site look. It can contain any combination of static text and controls. A master
page also contains one or more content placeholders that designate where dynamic content will appear when pages are
displayed.
In this walkthrough, you will use a table to help you position elements on the page. You will start by creating a layout table to
hold the master page elements. Later in this section you will position the content placeholder control that is already on the
page.
To create a layout table for the master page
1. With the Master1.master file selected in Source view, set the target schema for validation to Microsoft Internet Explorer
6.0. To set this value, you can use either the drop-down list on the toolbar or select Options from the Tools menu, and
then click Validation.
2. Switch to Design view.
3. From the drop-down list at the top of the Properties window, select DOCUMENT, and then set BgColor to a distinctive
color, such as blue.
The color you select is not important. Later in this walkthrough you will create a second master page without a color to
contrast with what you have selected here.
4. Click the page where you want to place the layout table.
Note
Do not put the layout table inside the ContentPlaceHolder control.

5. On the Layout menu, click Insert Table.


6. In the Insert Table dialog box, click Template. In the list click Header, footer and side, and then click OK.
The template defines the arrangement of rows and cells in the table. The template you have selected creates three rows,
and the middle row is split into two cells.
7. Make the following settings:
In the middle row, click the leftmost column, and then set its Width to 48 in the Properties window.
Click the top row, and then set its Height to 48 in the Properties window.
Click the bottom row, and then set its Height to 48 in the Properties window.
Note
You can set the width and height by dragging the table cell borders or by selecting the cell and setting values in the Pro
perties window.

8. Select all cells in the table and set BgColor to a different color than the background color, and set VAlign to top.
8. Select all cells in the table and set BgColor to a different color than the background color, and set VAlign to top.
After laying out the table, you can add content to the master page that will appear on all pages. You will add a copyright
message as a footer, and add a menu. If you have a logo graphic available, you can add that as well.
To add static content to the master page
1. Click the bottom cell, and then type footer text such as Copyright 2005 Contoso Inc.
2. In the Toolbox, from the Navigation control group, drag a Menu control into the top cell.
3. Create a menu by following these steps:
a. Set the Menu control's Orientation property to Horizontal.
b. Click the smart tag on the Menu control, and click Edit Menu Items in the Menu Tasks dialog box.
4. Under Items, click the Add a root node icon twice to add two menu items:
a. Click the first node, and then set Text to Home and NavigateUrl to Home.aspx.
b. Click the second node, and then set Text to About and NavigateUrl to About.aspx.
c. Click OK to close the Menu Item Editor dialog box.
5. If you have a graphics file available to use as a logo, follow these steps to place it on the master page:
a. In Solution Explorer, right-click the name of your Web site, and then click Add Existing Item.
b. Navigate to your graphics file, select the graphic file, and then click Add.
c. In the Toolbox, from the Standard group, drag an Image control to the middle left column of the table.
d. Set the Image control's ImageUrl property to the name of the graphics file.
You can now position the content placeholder to specify where the master page can display content at run time.
To add a content placeholder
1. Drag the ContentPlaceHolder control into the middle right cell.
The control's ID property is ContentPlaceholder1. You can leave this name or change it. If you change the name, make a
note of the name because you will need to know the name later.
2. Save the page.
Creating Content for the Master Page
The master page provides the template for your content. You define content for the master page by creating an ASP.NET page
that is associated with the master page. The content page is a specialized form of an ASP.NET page that contains only the
content to be merged with the master page. In the content page, you add the text and controls that you want to display when
users request that page.
In this walkthrough, you will add two pages with content for the master page. The first is a home page and the second is an
about page.
To create the Home page
1. In Solution Explorer, right-click the name of your Web site, and click Add New Item.
2. Under Visual Studio installed templates, click Web Form.
3. In the Name box, type Home.
4. In the Language list, click the programming language you prefer.
5. Select the Select master page check box, and then click Add.
The Select a Master Page dialog box appears.
6. Click Master1.master, and then click OK.
A new .aspx file is created. The page contains an @ Page directive that attaches the current page to the selected master
page with the MasterPageFile attribute, as shown in the following code example.
VB
<%@ Page Language="VB" MasterPageFile="~/Master1.master" ... %>

C#
<%@ Page Language="C#" MasterPageFile="~/Master1.master" ... %>

The page also contains an <asp:Content> element that you will work with next.
A content page does not have the usual elements that make up an ASP.NET page, such as html, body, or form elements.
Instead, you add only the content that you want to display on the master page by replacing the placeholder regions you
created in the master page.
To add content to the Home page
1. Switch to Design view.
The region you created as a ContentPlaceHolder control in the master page is displayed as a Content control in the
new content page. The rest of the master page content is displayed so you can see the layout, but it appears dimmed
because you cannot change it while editing a content page.
2. From the drop-down list in the Properties window, click DOCUMENT, and then set Title to Contoso Home Page.
You can set the title of each content page independently, so that the correct title is displayed in the browser when the
content is merged with the master page. The title information is stored in the content page's @ Page directive.
3. In the Content control, type Welcome to the Contoso Web Site, select the text, and then format the text as a Heading
1 by selecting the text and selecting Heading 1 from the Block Format drop-down list above the Toolbox.
4. Press ENTER to create a new blank line in the Content control, and then type Thank you for visiting our site.
The text you add here is not important; you can type any text that will help you recognize this page as the home page.
5. Save the page.
You can create the About page the same way you created the Home page.
To create the About page
1. Use the same steps that you used for the Home page to add a new content page named About.aspx.
Be sure to attach the new page to the Master1.master page as you did with the Home page.
2. Change the page's title to Contoso About Page.
3. In the content region, type About Contoso, and then format the text as a Heading 1 by selecting the text and selecting
Heading 1 from the Block Format drop-down list above the Toolbox.
4. Press ENTER to create a new line, and then type Since 1982, Contoso has provided high-quality software services.
5. Save the page.
Testing the Pages
You can test the pages by running them as you would any ASP.NET page.
To test the pages
1. Switch to the Home.aspx page, and then press CTRL+F5.
ASP.NET merges the content in the Home.aspx page with the layout in the Master1.master page into a single page and
displays the resulting page in the browser. Notice that the URL of the page is Home.aspx; there is no reference in the
browser to the master page.
2. Click the About link.
The About.aspx page is displayed. It is also merged with Master1.master page.
Referencing Master Page Members
Code in the content pages can reference members on the master page, including any public properties or methods and any
controls on the master page. In this part of the walkthrough, you will create a property on the master page, and then use the
value of the property in the content pages. The premise is that the company name for the Web site is stored as a property in
the master page, and any reference to the company name in the content pages is based on the master page property.
The first step is to add a property to the master page.
To add a property to the master page
1. Switch to or open the Master1.master page.
2. In Solution Explorer, right-click Master1.master, and then click View Code to open the code editor.
Note
By default, Visual Web Developer creates pages that use the code-behind model. If you prefer, you can create code by u
sing the single-file model. For more information, see ASP.NET Web Page Code Model.

3. Inside the class definition, type the following code.


VB
Public Property CompanyName() As String
Get
Return CType(ViewState("companyName"), String)
End Get
Set(ByVal Value As String)
ViewState("companyName") = Value
End Set
End Property

C#
public String CompanyName
{
get { return (String) ViewState["companyName"]; }
set { ViewState["companyName"] = value; }
}

The code creates a property named CompanyName for the master page. The value is stored in view state so that it is
persisted between postbacks.
4. Inside the class definition (but not inside the property code), add the following code.
VB
Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) _
Handles Me.Init
Me.CompanyName = "Contoso"
End Sub

C#
void Page_Init(Object sender, EventArgs e)
{
this.CompanyName = "Contoso";
}

For this example, you will hard-code the value of the CompanyName property into the page.
You can now modify the content page to use the master page's CompanyName property.
To reference the CompanyName property in the content page
1. Switch to or open the Home.aspx page.
2. Switch to Source view.
3. At the top of the page, underneath the @ Page directive, add the following @ MasterType directive:

<%@ MasterType virtualpath="~/Master1.master" %>

The directive binds the content page's Master property, which you will use shortly, to the Master1.master page.
4. Switch to Design view.
5. In the Content control, change the text to Welcome to the Web site of .
6. In the Toolbox, from the Standard group, drag a Label control onto the Content control, and place it after the static text
so that the text reads:
Welcome to the Web site of [Label]
7. Set the Label control's ID property to CompanyName.
8. In Solution Explorer, right-click Home.aspx, and then click View Code to open the code editor.
9. Inside the class definition, add the following code.
VB
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) _
Handles Me.Load
CompanyName.Text = Master.CompanyName
End Sub

C#
void Page_Load(Object sender, EventArgs e)
{
CompanyName.Text = Master.CompanyName;
}

The content page's Master property returns a reference to the master page as defined in the @ MasterType directive you
added in step 3.
You can now test the content page to be sure it is referencing the master page's CompanyName property correctly.
To test the reference to the master page property
1. Switch to or open the Home.aspx page, and then press CTRL+F5 to run the page.
The page is displayed in the browser, with the text Welcome to the Web site of Contoso
2. Close the browser.
3. Switch to or open the Master1.master code-behind page.
4. Change the Page_Init handler to assign a different company name to the property, as in the following code example.
VB
Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) _
Handles Me.Init
Me.CompanyName = "New Company Name"
End Sub
C#
void Page_Init(Object sender, EventArgs e)
{
this.CompanyName = "New Company Name";
}

5. Switch to the Home.aspx page, and then press CTRL+F5 to run it again.
This time, the updated company name appears in the page.
Notes
There are several other issues you should be aware of when working with a master page:
In a real-world application, you would probably store information such as the company name in the configuration file
and read it directly in the content pages. However, the scenario outlined here provides a simple illustration of how to
reference master page members in content pages.
You can access members on the master page even without including an @ MasterType directive. However, to do so, you
must cast the System.Web.UI.Page.Master property to the appropriate master page type (the Master property is null
if a page has no master page). For more information, see Working with ASP.NET Master Pages Programmatically.
You can reference controls on the master page by using the Master.FindControls method. For more information, see
Working with ASP.NET Master Pages Programmatically.
Changing Master Pages Dynamically
Under some circumstances, you might want to be able to change master pages dynamically; that is, to use code to set the
master page for a content page. For example, you might want to let users select from several layouts and set the master page
according to their preferences.
In this part of the walkthrough, you will add a second master page to the Web site, and then create buttons that allow the user
to switch between one master page and another. Because the two master pages will be very similar, you will make a copy of
the first master page and modify it to act as the second master page.
To make a copy of the master page
1. In Solution Explorer, right-click Master1.master, and then click Copy.
2. Right-click the name of the Web site, and then click Paste.
A master page is added to the Web site with the name Copy of master1.master.
3. Right-click Copy of master1.master, click Rename, and then name the new master page Master2.master.
4. Open Master2.master and, in the @ Master directive, change Master1 to Master2.
The completed page directive will look like the following code example.
VB
<%@ Master Language="VB" CodeFile="Master2.master.vb" Inherits="Master2" %>

C#
<%@ Master Language="C#" CodeFile="Master2.master.cs" Inherits="Master2" %>

5. Switch to Design view.


6. In the Properties window, in the drop-down list at the top, click DOCUMENT.
7. Clear the BgColor property.
The new master page will look and function like Master1.master, but will have no background color.
8. Open the code file for Master2.master and change the class name in the master page's code-behind file from Master1 to
Master2 to match the value of the Inherits attribute in the page's <%@ Master %> directive.

The code will look like the following example.


VB
Partial Class Master2

C#
public partial class Master2 : System.Web.UI.MasterPage

The next step is to add a button to each master page that allows the user to select the alternate master page.
To add buttons for selecting an alternate master page
1. Switch to or open the Master2.master page.
2. In the Toolbox, from the Standard node, drag a LinkButton control onto the page and place it below the menu in the
top table cell.
3. Set the button's Text property to Colorful.
4. Double-click the button to create a handler for its Click event, and then add the following highlighted code.
VB
Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As EventArgs)_
Handles LinkButton1.Click
Session("masterpage") = "Master1.master"
Response.Redirect(Request.Url.ToString())
End Sub

C#
void LinkButton1_Click(Object sender, EventArgs e)
{
Session["masterpage"] = "Master1.master";
Response.Redirect(Request.Url.ToString());
}

The code loads the file name of the alternate master page into a persistent session variable, and then reloads the current
page. (The Url property returns a Uri object that references the current page.) Shortly, you will create code in the content
page that will use the name of the master page.
5. Switch to or open the Master1.master page in Design view.
6. Add a LinkButton control as you did in steps 1 and 2, and set its Text property to Plain.
7. Double-click the Plain button to create a handler for its Click event, and then add the following highlighted code.
VB
Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As EventArgs)_
Handles LinkButton1.Click
Session("masterpage") = "Master2.master"
Response.Redirect(Request.Url.ToString())
End Sub

C#
void LinkButton1_Click(Object sender, EventArgs e)
{
Session["masterpage"] = "Master2.master";
Response.Redirect(Request.Url.ToString());
}

This code is the same as that for the button in the Master2.master page, except that it loads an alternate master page.
You now write code in the content page that will dynamically load the master page that the user has selected.
To write code to dynamically select the master page
1. Switch to or open the About.aspx page.
Note
The Home page you have already created contains an @ MasterType directive that effectively binds it to a single maste
r page (Master1.master). Therefore, you will not be able to assign master pages dynamically to the Home page and will
instead work with other pages you have created.

2. In Solution Explorer, right-click About.aspx, and then click View Code to open the code editor.
3. Inside the class definition, add the following code.
VB
Sub Page_PreInit(ByVal sender As Object, ByVal e As EventArgs) _
Handles Me.PreInit
If Not Session("masterpage") Is Nothing Then
Me.MasterPageFile = CType(Session("masterpage"), String)
End If
End Sub

C#
void Page_PreInit(Object sender, EventArgs e)
{
if(Session["masterpage"] != null)
{
this.MasterPageFile = (String) Session["masterpage"];
}
}

The code sets the value of the current page's MasterPageFile property to the value in the session variable, if any. This
code must run in the Page_PreInit handler; it cannot run in a handler that occurs any later than the Page_PreInit
handler (for example, in the Page_Init handler), because the master page must be established so that the page can
create an instance of it before any further initialization can occur.
You can now test the dynamic master pages.
To test the dynamic master pages
1. In the About.aspx page, press CTRL+F5 to run the page.
The page is displayed in the browser merged with its default master page, Master1.master.
2. Click the Plain link.
The page is redisplayed, this time merged with Master2.master, which has no background color.
3. Click the Colorful link.
The page is displayed using Master1.master again.
Notes
There are several other issues you should be aware of when working with dynamic master pages:
The scenario in this section for changing master pages is simplified to keep the walkthrough focused on master pages. In
a real application, you would most likely display a choice of layouts, and then store the user's preference by using
profiles. For details, see ASP.NET Profile Properties Overview.
You can configure your Web site so that all pages use the same master page. You might have a few pages that should
use an alternate master page, which you can configure in code in a manner similar to that shown in this section of the
walkthrough. For details, see "Scoping Master Pages" in ASP.NET Master Pages Overview.
You need to add the code from the Home.aspx page to every page where you want to override the default master page.
Next Steps
This walkthrough illustrates the basic functionality of master pages. You might want to experiment with additional features of
master pages. For example, you might want to:
Create master pages that have multiple content placeholders. You can then fill one or more placeholders with content for
each page that you display.
Define content placeholders with default content. If an ASP.NET page does not supply content for the placeholder, the
master page displays the default content.
Programmatically access members of the master page from content pages. This allows you to dynamically change the
look of the master page at run time. For details, see How to: Reference ASP.NET Master Page Content.
Use device filtering with master pages to create different layouts for different devices, such as one layout for browsers
and another for a specific type of phone. For details, see ASP.NET Device Filtering Overview.
Learn how you can put master pages within master pages to create componentized pieces. For details, see
Nested ASP.NET Master Pages.
See Also
Concepts
ASP.NET Master Pages Overview
Events in ASP.NET Master and Content Pages
Visual Web Developer

Walkthrough: Creating a Basic ASP.NET Wizard Control


Building a series of forms to collect user data is a common task when developing Web sites. The ASP.NET Wizard control
simplifies many of the tasks associated with building forms and collecting user input by providing a mechanism that allows
you to easily build steps, add a new step, or reorder the steps. In this walkthrough, you will use the ASP.NET Wizard control to
simplify data collection as a series of independent steps without having to write code or making user data persist between
form steps. You will create a simple wizard that collects a user name and e-mail address, and then present it back to the user in
the completion step. Tasks illustrated in this walkthrough include:
Adding a Wizard control to your page.
Adding controls and text to a wizard step.
Accessing the wizard's data between steps.
Prerequisites
In order to complete this walkthrough, you will need:
Microsoft Visual Web Developer (Visual Studio).
The .NET Framework.
Creating the Web Site
If you have already created a Web site in Visual Web Developer (for example, by following the steps in
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and skip to "Adding a Wizard
Control" later in this walkthrough. Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of your Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Adding a Wizard Control
To add a Wizard control
1. Switch to Design view for Default.aspx.
2. From the Standard group of the Toolbox, drag a Wizard control onto the page.
The control appears with two default steps already in place. Clicking the steps allows you to edit the text and controls
displayed during that step.
Editing Wizard Steps
When the Wizard control is dragged onto the page, it shows two predefined steps by default. For this walkthrough, you will
edit both steps, and add a completion step that shows the result of the first two steps: a user name and an e-mail address.
To edit the first wizard step
1. Drag one of the handles at the edge of the Wizard control to enlarge the control to about twice its default size.
2. Click the underlined text Step 1 in the Wizard control.
3. Click the edit area for the Wizard control.
You can now edit the step's display area.
4. Type Name:.
5. Drag a TextBox control onto the active area of the wizard, next to the text you just typed.
You can now edit the second step to collect a user's e-mail address.
To edit the second wizard step
1. Click Step 2 in the Wizard control.
2. Click the edit area for the Wizard control.
3. Type Email:.
4. Drag a TextBox control onto the active area of the wizard, next to your e-mail label.
5. Save the file.
Adding a Completion Step
You will now create a completion step that acts as the end point of your wizard. The Complete step has no navigational
options.
To add a completion step
1. Right-click the Wizard control.
2. Choose Show Smart Tag.
3. In the Wizard Tasks dialog box, choose Add/Remove Wizard Steps.
The WizardStep Collection Editor appears.
4. From the Add drop-down list on the Add button, select Wizard Step.
The Properties area now shows the new step.
5. Set the Title property to Finished.
6. Set the StepType property to Complete.
7. Click OK.
Now you can edit your new completion step. For the purposes of this walkthrough, configure the completion step to show the
data the user entered on the previous steps.
To edit the completion step
1. Right-click the Wizard control and choose Show Smart Tag.
2. In the Wizard Tasks dialog box, use the Step drop-down list to choose the Finished step.
Note
The name in the drop-down list will be the name you gave the step when you created it, Finished in this example.

3. Drag a Label control onto the wizard, leaving the default name of Label1.
4. Drag another Label control onto the wizard, leaving the default name of Label2.
5. Save the file.
The completion step will display the data entered by the user. Use the page's Load event to assign the values from the first two
steps to the labels you added to the completion step.
To show the user's data
1. Return to Default.aspx and, in Design view, double-click the design surface.
The page now contains a Page_Load method that is stubbed out for you.
2. Add the following highlighted code.
VB
Private Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles Me.Load
Label1.Text = TextBox1.Text
Label2.Text = TextBox2.Text
End Sub

C#
void Page_Load(Object sender, System.EventArgs e)
{
Label1.Text = TextBox1.Text;
Label2.Text = TextBox2.Text;
}

3. Save the file.


Testing the Wizard Control
Now you can test the Wizard control.
To test the Wizard control
1. View Default.aspx in Design view.
2. Display the Wizard Tasks menu on the control and select Step 1 from the Step drop-down list.
3. Click the Wizard control, and then press CTRL+F5.
4. Type a name in the name TextBox control for Step 1.
5. Click Next.
6. Type an e-mail address in the e-mail TextBox control for Step 2.
7. Click Finish.
Your data is displayed.
Next Steps
The Wizard control simplifies the creation of forms to gather user data. In addition to what has been covered here, you might
have other questions related to user data collection and forms use. For example, you might want to:
Learn more about authenticating users with Forms. For details, see How to: Implement Simple Forms Authentication
Use themes to enhance the appearance of your wizard. For details, see ASP.NET Themes and Skins Overview
Get an overview of the Wizard control. For details, see Wizard Web Server Control Overview
See Also
Reference
Wizard Web Server Control Overview
Visual Web Developer

Walkthrough: Creating a Web Parts Page in Visual Web


Developer
This walkthrough is a hands-on demonstration of the essential components and tasks for creating Web pages that use Web
Parts controls in a visual page design tool such as Microsoft Visual Studio.
In many Web applications it is useful to be able to change the appearance of the content, as well as to allow users to select and
arrange the content they want to see. ASP.NET Web Parts enable you to create Web pages that present modular content and
that enable users to change the appearance and content to suit their preferences. For a general introduction to Web Parts, see
ASP.NET Web Parts Overview. For an overview of the Web Parts control set, see Web Parts Control Set Overview.
During this walkthrough, you create a page that uses Web Parts controls to create a Web page that user can modify, or
personalize. Tasks illustrated in this walkthrough include:
Adding Web Parts controls to a page.
Creating a custom user control and using it as a Web Parts control.
Allowing users to personalize the layout of the Web Parts controls on the page.
Allowing users to edit the appearance of a Web Parts control.
Allowing users to select from a catalog of available Web Parts controls.
Prerequisites
In order to complete this walkthrough, you will need:
A site that can identify individual users. If you have a site already configured with ASP.NET membership, you can use that
site for this walkthrough. Otherwise, the walkthrough provides instructions on how to configure your site to identify you
by your Windows user account name.
A visual design environment for creating Web pages. This walkthrough uses Visual Studio.
A configured personalization provider and database. Web Parts personalization is enabled by default, and it uses the SQL
personalization provider (SqlPersonalizationProvider) with Microsoft SQL Server Express Edition to store personalization
data. This walkthrough uses SQL Server Express and the default SQL provider. If you have SQL Server Express installed,
no configuration is needed. SQL Server Express is available with Microsoft Visual Studio 2005 as an optional part of the
installation, or as a free download from Microsoft.com. To use a full version of SQL Server, you must install and configure
an ASP.NET application services database, and configure the SQL personalization provider to connect to that database.
For details, see Creating and Configuring the Application Services Database for SQL Server.
Creating and Configuring the Web Site
This walkthrough requires that you have a user identity, so that your Web Parts settings can be keyed to you. If you already
have a Web site configured to use membership, it is recommended that you use that site. Otherwise, you can create a new site
and use your current Windows user name as your user identity.
To create a new Web site
In Visual Studio, create a new ASP.NET Web site. For details, see
Walkthrough: Creating a Web Site with Membership and User Login (Visual Studio).
Creating a Simple Page with Web Parts
In this part of the walkthrough, you create a page that uses Web Parts controls to show static content. The first step in working
with Web Parts is to create a page with two required elements. First, a Web parts page needs a WebPartManager control to
coordinate all Web Parts controls. Second, a Web Parts page needs one or more zones, which are composite controls that
contain WebPart or other server controls and occupy a specified region of a page.
Note
You do not need to do anything to enable Web Parts personalization; it is enabled by default for the Web Parts control set. W
hen you first run a Web Parts page on a site, ASP.NET sets up a default personalization provider to store user personalization
settings. For more information about personalization, see Web Parts Personalization Overview.

To create a page for containing Web Parts controls


1. Close the default page and add a new page named WebPartsDemo.aspx.
2. Switch to Design view.
3. From the View menu, make sure that the Non-Visual Controls and Details options are selected so you can see layout
tags and controls that do not have a UI.
4. Place the insertion point before the <div> tags on the design surface, and press ENTER to add a new line.
5. Position the insertion point before the new line character. From the Block Format list in the toolbar, select Heading 1
and in the heading, add the text Web Parts Demonstration Page.
6. From the WebParts tab of the Toolbox, drag a WebPartManager control onto the page, between the new line character
and the opening <div> tag.
The WebPartManager control does not render any output, so it appears as a gray box on the designer surface.
7. Position the insertion point within the <div> tags.
8. In the Layout menu, click Insert Table, and create a new table that has one row and three columns. Click the Cell
Properties button, select top from the Vertical align drop-down list, click OK, and click OK again to create the table.
9. Drag a WebPartZone control into the left table column. Right-click the WebPartZone control, choose Properties, and
set the following properties:
ID: SidebarZone

HeaderText: Sidebar

10. Drag a second WebPartZone control into the middle table column and set the following properties:
ID: MainZone

HeaderText: Main

11. Save the file.


Your page now has two distinct zones that you can control separately. However, neither zone has any content, so creating
content is the next step. For this walkthrough, you work with Web Parts controls that display only static content.
The layout of a Web Parts zone is specified by a <zonetemplate> element. Inside the zone template, you can add any
ASP.NET control, whether it is a custom Web Parts control, a user control, or an existing server control. Notice that here you are
using the Label control, and to that you are simply adding static text. When you place a regular server control in a
WebPartZone zone, ASP.NET treats the control as a Web Parts control at run time, which enables Web Parts features on the
control.
To create content for the main zone
1. In Design view, drag a Label control from the Standard tab of the Toolbox into the contents area of the zone whose ID
property is set to MainZone.
2. Switch to Source view.
Notice that a <zonetemplate> element was added to wrap the Label control in the MainZone.
3. Add an attribute named title to the <asp:label> element, and set its value to Content. Remove the Text="Label"
attribute from the <asp:label> element. Inside the <asp:label> element, add some text such as <h2>Welcome to my
Home Page</h2>. Your code should look as follows:

<asp:webpartzone id="MainZone" runat="server" headertext="Main">


<zonetemplate>
<asp:label id="Label1" runat="server" title="Content">
<h2>Welcome to My Home Page</h2>
</asp:label>
</zonetemplate>
</asp:webpartzone>

4. Save the file.


Next, create a user control that can also be added to the page as a Web Parts control.
To create a user control
1. Add a new Web user control to your site to serve as a search control named SearchUserControl.ascx, making sure that
the Place source code in a separate file is cleared.
Note
The user control for this walkthrough does not implement actual search functionality; it is used only to demonstrate W
eb Parts features.

2. Switch to Design view.


3. From the Standard tab of the Toolbox, drag a TextBox control onto the page.
4. Place the insertion point after the text box you just added, and press ENTER to add a new line.
5. Drag a Button control onto the page on the new line below the text box you just added.
6. Switch to Source view and then ensure that the source code for the user control looks like the following example:
VB
<%@ control language="VB" classname="SearchUserControl" %>
<asp:textbox runat="server" id="TextBox1"></asp:textbox>
<br />
<asp:button runat="server" id="Button1" text="Search" />

C#
<%@ control language="C#" classname="SearchUserControl" %>
<asp:textbox runat="server" id=" TextBox1"></asp:textbox>
<br />
<asp:button runat="server" id=" Button1" text="Search" />

7. Save and close the file.


Security Note
This control has a textbox that accepts user input, which is a potential security threat. User input in a Web page can pot
entially contain malicious client script. By default, ASP.NET Web pages validate user input to ensure that the input does
not contain HTML elements or script. As long as this validation is enabled, you do not need to explicitly check for script
or HTML elements in user input. For more information, see Script Exploits Overview.

Now you can add Web Parts controls to the Sidebar zone. You are adding two controls to the Sidebar zone, one containing a
list of links and another that is the user control you created earlier in the walkthrough. The links are added as a standard Label
server control, similar to the way you created the static text for the Main zone. However, although the individual server controls
contained in the user control could be contained directly in the zone (like the label control), in this case they are not. Instead,
they are part of the user control you created in the previous procedure. This demonstrates a common way to package controls
and extra functionality you want in a user control, and then reference that control in a zone as a Web Parts control.
At run time, the Web Parts control set wraps both controls with GenericWebPart controls. When a GenericWebPart control
wraps a Web server control, the generic part control is the parent control, and you can access the server control through the
parent control's ChildControl property. Using generic part controls enables standard Web server controls to have the same
basic behavior and attributes as Web Parts controls that derive from the WebPart class.
To add Web Parts controls to the sidebar zone
1. Open the WebPartsDemo.aspx page.
2. Switch to Design view.
3. Drag the user control page you created, SearchUserControl.ascx, from Solution Explorer into the zone whose ID
property is set to SidebarZone.
4. Save the WebPartsDemo.aspx page.
5. Switch to Source view.
6. Inside the <asp:webpartzone> element for the SidebarZone, add an <asp:label> element that contains links and in the
user control tag, add a Title attribute with a value of Search, as shown in the following example:

<asp:WebPartZone id="SidebarZone" runat="server"


headertext="Sidebar">
<zonetemplate>
<asp:label runat="server" id="linksPart" title="My Links">
<a href="http://www.asp.net">ASP.NET site</a>
<br />
<a href="http://www.gotdotnet.com">GotDotNet</a>
<br />
<a href="http://www.contoso.com">Contoso.com</a>
<br />
</asp:label>
<uc1:SearchUserControl id="searchPart" runat="server"
title="Search" />
</zonetemplate>
</asp:WebPartZone>

7. Save and close the file.


Now you can test your page.
To test the page
Load the page in a browser.
The page displays the two zones. The following screen shot shows the page.
Web Parts Demo page with two zones
In the title bar of each control is a downward arrow that provides access to a verbs menu of available actions you can
perform on a control. Click the verbs menu for one of the controls, then click the Minimize verb and note that the
control is minimized. From the verbs menu, click Restore, and the control returns to its normal size.
Enabling Users to Edit Pages and Change Layout
Web Parts provides the capability for users to change the layout of Web Parts controls by dragging them from one zone to
another. In addition to allowing users to move WebPart controls from one zone to another, you can allow users to edit various
characteristics of the controls, including their appearance, layout, and behavior. The Web Parts control set provides basic
editing functionality for WebPart controls. Although you will not do so in this walkthrough, you can also create custom editor
controls that allow users to edit the features of WebPart controls. As with changing the location of a WebPart control, editing
a control's properties relies on ASP.NET personalization to save the changes that users make.
In this part of the walkthrough, you add the ability for users to edit the basic characteristics of any WebPart control on the
page. To enable these features, you add another custom user control to the page, along with an <asp:editorzone> element
and two editing controls.
To create a user control that enables changing page layout
1. In Visual Studio, on the File menu, click New, and then click File.
2. In the Add New Item dialog, select Web User Control. Name the new file DisplayModeMenu.ascx. Clear the Place
source code in separate file box.
3. Click Add to create the new control.
4. Switch to Source view.
5. Remove all the existing code in the new file, and paste in the following code. This user control code uses features of the
Web Parts control set that enable a page to change its view or display mode, and also enables you to change the physical
appearance and layout of the page while you are in certain display modes.
VB
<%@ control language="vb" classname="DisplayModeMenuVB"%>
<script runat="server">
' Use a field to reference the current WebPartManager control.
Dim _manager As WebPartManager

Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)


AddHandler Page.InitComplete, AddressOf InitComplete
End Sub

Sub InitComplete(ByVal sender As Object, ByVal e As System.EventArgs)


_manager = WebPartManager.GetCurrentWebPartManager(Page)

Dim browseModeName As String = _


WebPartManager.BrowseDisplayMode.Name
' Fill the drop-down list with the names of supported display modes.
Dim mode As WebPartDisplayMode
For Each mode In _manager.SupportedDisplayModes
Dim modeName As String = mode.Name
' Make sure a mode is enabled before adding it.
If mode.IsEnabled(_manager) Then
Dim item As New ListItem(modeName, modeName)
DisplayModeDropdown.Items.Add(item)
End If
Next mode

' If Shared scope is allowed for this user, display the


' scope-switching UI and select the appropriate radio button
' for the current user scope.
If _manager.Personalization.CanEnterSharedScope Then
Panel2.Visible = True
If _manager.Personalization.Scope = _
PersonalizationScope.User Then
RadioButton1.Checked = True
Else
RadioButton2.Checked = True
End If
End If
End Sub

' Change the page to the selected display mode.


Sub DisplayModeDropdown_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As EventArgs)

Dim selectedMode As String = DisplayModeDropdown.SelectedValue


Dim mode As WebPartDisplayMode = _
_manager.SupportedDisplayModes(selectedMode)
If Not (mode Is Nothing) Then
_manager.DisplayMode = mode
End If
End Sub

' Set the selected item equal to the current display mode.
Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs)
Dim items As ListItemCollection = DisplayModeDropdown.Items
Dim selectedIndex As Integer = _
items.IndexOf(items.FindByText(_manager.DisplayMode.Name))
DisplayModeDropdown.SelectedIndex = selectedIndex
End Sub

' Reset all of a user's personalization data for the page.


Protected Sub LinkButton1_Click(ByVal sender As Object, _
ByVal e As EventArgs)

_manager.Personalization.ResetPersonalizationState()

End Sub

' If not in User personalization scope, toggle into it.


Protected Sub RadioButton1_CheckedChanged(ByVal sender As _
Object, ByVal e As EventArgs)
If _manager.Personalization.Scope = _
PersonalizationScope.Shared Then
_manager.Personalization.ToggleScope()
End If
End Sub

' If not in Shared scope, and if user has permission, toggle the
' scope.
Protected Sub RadioButton2_CheckedChanged(ByVal sender As _
Object, ByVal e As EventArgs)
If _manager.Personalization.CanEnterSharedScope AndAlso _
_manager.Personalization.Scope = _
PersonalizationScope.User Then
_manager.Personalization.ToggleScope()
End If
End Sub

</script>
<div>
<asp:Panel ID="Panel1" runat="server"
Borderwidth="1"
Width="230"
BackColor="lightgray"
Font-Names="Verdana, Arial, Sans Serif" >
<asp:Label ID="Label1" runat="server"
Text="&nbsp;Display Mode"
Font-Bold="true"
Font-Size="8"
Width="120" />
<asp:DropDownList ID="DisplayModeDropdown" runat="server"
AutoPostBack="true"
Width="120"
OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
<asp:LinkButton ID="LinkButton1" runat="server"
Text="Reset User State"
ToolTip="Reset the current user's personalization data for
the page."
Font-Size="8"
OnClick="LinkButton1_Click" />
<asp:Panel ID="Panel2" runat="server"
GroupingText="Personalization Scope"
Font-Bold="true"
Font-Size="8"
Visible="false" >
<asp:RadioButton ID="RadioButton1" runat="server"
Text="User"
AutoPostBack="true"
GroupName="Scope"
OnCheckedChanged="RadioButton1_CheckedChanged" />
<asp:RadioButton ID="RadioButton2" runat="server"
Text="Shared"
AutoPostBack="true"
GroupName="Scope"
OnCheckedChanged="RadioButton2_CheckedChanged" />
</asp:Panel>
</asp:Panel>
</div>

C#
<%@ control language="C#" classname="DisplayModeMenuCS"%>
<script runat="server">

// Use a field to reference the current WebPartManager control.


WebPartManager _manager;

void Page_Init(object sender, EventArgs e)


{
Page.InitComplete += new EventHandler(InitComplete);
}

void InitComplete(object sender, System.EventArgs e)


{
_manager = WebPartManager.GetCurrentWebPartManager(Page);

String browseModeName = WebPartManager.BrowseDisplayMode.Name;

// Fill the drop-down list with the names of supported display modes.
foreach (WebPartDisplayMode mode in
_manager.SupportedDisplayModes)
{
String modeName = mode.Name;
// Make sure a mode is enabled before adding it.
if (mode.IsEnabled(_manager))
{
ListItem item = new ListItem(modeName, modeName);
DisplayModeDropdown.Items.Add(item);
}
}

// If Shared scope is allowed for this user, display the


// scope-switching UI and select the appropriate radio
// button for the current user scope.
if (_manager.Personalization.CanEnterSharedScope)
{
Panel2.Visible = true;
if (_manager.Personalization.Scope ==
PersonalizationScope.User)
RadioButton1.Checked = true;
else
RadioButton2.Checked = true;
}
}

// Change the page to the selected display mode.


void DisplayModeDropdown_SelectedIndexChanged(object sender,
EventArgs e)
{
String selectedMode = DisplayModeDropdown.SelectedValue;

WebPartDisplayMode mode =
_manager.SupportedDisplayModes[selectedMode];
if (mode != null)
_manager.DisplayMode = mode;
}

// Set the selected item equal to the current display mode.


void Page_PreRender(object sender, EventArgs e)
{
ListItemCollection items = DisplayModeDropdown.Items;
int selectedIndex =
items.IndexOf(items.FindByText(_manager.DisplayMode.Name));
DisplayModeDropdown.SelectedIndex = selectedIndex;
}

// Reset all of a user's personalization data for the page.


protected void LinkButton1_Click(object sender, EventArgs e)
{
_manager.Personalization.ResetPersonalizationState();
}

// If not in User personalization scope, toggle into it.


protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (_manager.Personalization.Scope ==
PersonalizationScope.Shared)
_manager.Personalization.ToggleScope();
}

// If not in Shared scope, and if user has permission, toggle


// the scope.
protected void RadioButton2_CheckedChanged(object sender,
EventArgs e)
{
if (_manager.Personalization.CanEnterSharedScope &&
_manager.Personalization.Scope ==
PersonalizationScope.User)
_manager.Personalization.ToggleScope();
}
</script>
<div>
<asp:Panel ID="Panel1" runat="server"
Borderwidth="1"
Width="230"
BackColor="lightgray"
Font-Names="Verdana, Arial, Sans Serif" >
<asp:Label ID="Label1" runat="server"
Text="&nbsp;Display Mode"
Font-Bold="true"
Font-Size="8"
Width="120" />
<asp:DropDownList ID="DisplayModeDropdown" runat="server"
AutoPostBack="true"
Width="120"
OnSelectedIndexChanged="DisplayModeDropdown_SelectedIndexChanged" />
<asp:LinkButton ID="LinkButton1" runat="server"
Text="Reset User State"
ToolTip="Reset the current user's personalization data for
the page."
Font-Size="8"
OnClick="LinkButton1_Click" />
<asp:Panel ID="Panel2" runat="server"
GroupingText="Personalization Scope"
Font-Bold="true"
Font-Size="8"
Visible="false" >
<asp:RadioButton ID="RadioButton1" runat="server"
Text="User"
AutoPostBack="true"
GroupName="Scope"
OnCheckedChanged="RadioButton1_CheckedChanged" />
<asp:RadioButton ID="RadioButton2" runat="server"
Text="Shared"
AutoPostBack="true"
GroupName="Scope"
OnCheckedChanged="RadioButton2_CheckedChanged" />
</asp:Panel>
</asp:Panel>
</div>

6. Save the file.


Note
Although this user control can enable users of the Web Parts page to toggle between shared and user-personalization
mode, this feature requires the user to have appropriate permissions, as specified in the Web.config file. This walkthrou
gh does not illustrate how to grant these rights, so the feature is not enabled. Therefore, the user and shared radio butt
ons on the user control are hidden when you run the page. For more information on personalization, see
Web Parts Personalization.

To enable users to change the layout


1. Open the WebPartsDemo.aspx page.
2. Switch to Design view.
3. Position the insertion point just after the WebPartManager control that you added earlier. Press ENTER to create a
blank line after the WebPartManager control.
4. Drag the user control you just created (DisplayModeMenu.ascx) into the WebPartsDemo.aspx page and drop it on the
blank line.
5. Drag an EditorZone control from the WebParts tab of the Toolbox to the remaining open table cell in the
WebPartsDemo.aspx page.

6. From the WebParts tab of the Toolbox, drag an AppearanceEditorPart control and a LayoutEditorPart control into the
EditorZone control.
7. Switch to Source view.
The resulting code in the table cell will look similar to the following code.

<td valign="top">
<asp:EditorZone ID="EditorZone1" runat="server">
<ZoneTemplate>
<asp:AppearanceEditorPart ID="AppearanceEditorPart1"
runat="server" />
<asp:LayoutEditorPart ID="LayoutEditorPart1" runat="server" />
</ZoneTemplate>
</asp:EditorZone>
</td>

Note
Although the AppearanceEditorPart and LayoutEditorPart controls are used in this walkthrough, the
BehaviorEditorPart and PropertyGridEditorPart controls are not, because they require setup beyond the scope of this w
alkthrough.

8. Save the WebPartsDemo.aspx file.


You have created a user control that allows you to change display modes and change page layout, and you have referenced the
control on the primary Web page.
You can now test the capability to edit pages and change layout.
To test layout changes
1. Load the page in a browser.
2. In the Display Mode menu, click Edit.
The zone titles are displayed.
3. Drag the My Links control by its title bar from the Sidebar zone to the bottom of the Main zone.
The page will look like the following:
Web Parts Demo page with My Links control moved

4. Click Display Mode, and then click Browse.


The page is refreshed, the zone names disappear, and the My Links control remains where you positioned it.
5. To demonstrate that personalization is working, close the browser, and then load the page again. The changes you made
are saved for future browser sessions.
6. In the Display Mode menu, click Edit.
Each control on the page is now displayed with a downward arrow in its title bar, which contains the verbs drop-down
menu.
7. Click the arrow to display the verbs menu on the My Links control and then click Edit.
The EditorZone control appears, displaying the EditorPart controls you added.
8. In the Appearance section of the edit control, change the Title to My Favorites. In the Chrome Type list, select Title
Only, and then click Apply.
The following screen shot shows the page in edit mode.
Web Parts Demo page in Edit mode
9. In the Display Mode menu, click Browse to return to browse mode.
The control now has an updated title and no border, as shown in the following screen shot.
Edited Web Parts Demo page

Adding Web Parts at Run Time


You can also enable users to add Web Parts controls to their page at run time. To do so, configure the page with a Web Parts
catalog, which contains a list of Web Parts controls that you want to make available to users.
Note
In this walkthrough, you create a template containing FileUpload and Calendar controls. This will allow you to test the basic f
unctionality of the catalog, but the resulting Web Parts controls do not have any real functionality. If you have a custom Web
or user control, you can substitute it for the static content.

To allow users to add Web Parts at run time


1. Open the WebPartsDemo.aspx page.
2. Switch to Design view.
3. From the WebParts tab of the Toolbox, drag a CatalogZone control into the right column of the table, beneath the
EditorZone control.
Both controls can be in the same table cell because they will not be displayed at the same time.
4. In the Properties pane, assign the string Add Web Parts to the HeaderText property of the CatalogZone control.
5. From the WebParts tab of the Toolbox, drag a DeclarativeCatalogPart control into the content area of the CatalogZone
control.
6. Click the arrow in the upper right corner of the DeclarativeCatalogPart control to expose its Tasks menu, and then
select Edit Templates.
7. From the Standard tab of the Toolbox, drag a FileUpload control and a Calendar control into the WebPartsTemplate
section of the DeclarativeCatalogPart control.
8. Switch to Source view and inspect the source code of the <asp:catalogzone> element.
Notice that the DeclarativeCatalogPart control contains a <webpartstemplate> element with the two enclosed
server controls that you will be able to add to your page from the catalog.
Note
If you have a custom control, this is the place to substitute it for one of the server controls in the example, although this
requires steps beyond the scope of this walkthrough. For further details, see the code example in the documentation fo
r the WebPart class.

9. Add a Title property to each of the controls you added to the catalog, using the string value shown for each title in the
code example below. Even though the title is not a property you can normally set on these two server controls at design
time, when a user adds these controls to a WebPartZone zone from the catalog at run time, they are each wrapped with
a GenericWebPart control. This enables them to act as Web Parts controls, so they will be able to display titles.
The code for the two controls contained in the DeclarativeCatalogPart control will look like the following.

<asp:DeclarativeCatalogPart ID="DeclarativeCatalogPart1"
runat="server">
<WebPartsTemplate>
<asp:Calendar ID="Calendar1"
runat="server"
title="My Calendar" />
<asp:FileUpload ID="FileUpload1"
runat="server"
title="Upload Files" />
</WebPartsTemplate>
</asp:DeclarativeCatalogPart>

10. Save the page.


You can now test the catalog.
To test the Web Parts catalog
1. Load the page in a browser.
2. In the Display Mode menu, click Catalog.
The catalog titled Add Web Parts is displayed.
3. Drag the My Favorites control from the Main zone back to the top of the Sidebar zone.
4. In the Add Web Parts catalog, select both check boxes, and then select Main from the list of available zones
5. Click Add in the catalog.
The controls are added to the Main zone. If you want, you can add multiple instances of controls from the catalog to your
page. The following screen shot shows the page with the file upload control and the calendar in the Main zone:
Controls added to Main zone from the catalog
6. In the Display Mode menu, click Browse.
The catalog disappears and the page is refreshed.
7. Close the browser and then Load the page again.
The changes you made persist.
Next Steps
This walkthrough has illustrated the basic principles of using simple Web Parts controls on an ASP.NET Web page. You might
want to experiment with additional, more sophisticated Web Parts features. Suggestions for further exploration include:
Create Web Parts controls that offer more sophisticated functionality than the static Web Parts from this walkthrough.
You can create Web Parts controls as user controls or custom controls. For details, see the documentation for the
WebPart class.
See Also
Tasks
Walkthrough: Creating a Web Parts Page
Reference
Web Parts Control Set Overview
WebPart
Concepts
ASP.NET Web Parts Overview
Visual Web Developer

Customizing Web Pages


The topics in this section include step-by-step walkthroughs that illustrate how to add menus, define themes for consistent
Web site appearance, create rotating advertisements, create pages for browsers on mobile devices, create and use an ASP.NET
Web service, and create pages that can display text in different languages.
In This Section
Walkthrough: Adding Site Navigation to a Web Site
Walkthrough: Creating a Web Site with Membership and User Login (Visual Studio)
Walkthrough: Maintaining Web Site User Information with Profile Properties
Walkthrough: Customizing a Web Site Using Themes in Visual Studio
Walkthrough: Displaying and Tracking Advertisements with the AdRotator Control
Walkthrough: Creating and Using an ASP.NET Web Service in Visual Web Developer
Walkthrough: Creating Web Pages for Mobile Devices
Walkthrough: Using Resources for Localization with ASP.NET
Related Sections
Guided Tour of Creating Web Sites in Visual Web Developer
Introduces topics designed to give a guided tour of creating Web sites in Microsoft Visual Web Developer.
Visual Web Developer

Walkthrough: Adding Site Navigation to a Web Site


In any site that has more than just several pages, it can be difficult to construct a navigation system that lets users move freely
between pages, especially as you change the site. ASP.NET site navigation lets you create a centralized site map of the pages.
This walkthrough shows you how to configure a site map and how to use controls that rely on the site map to add navigation
to pages in the Web site.
During this walkthrough, you will learn how to do the following:
Create a Web site that has example pages and a site-map file that describes the layout of the pages.
Use the TreeView control as a navigation menu that lets users jump to any page in your site.
Use the SiteMapPath control to add a navigation path, also known as a breadcrumb, that enables a user to view and
move back up the site hierarchy from the current page.
Use the Menu control to add a navigation menu that lets users view one level of nodes at a time. Pausing the mouse
pointer over a node that has child nodes generates a submenu of the child nodes.
Use site navigation and controls on a master page so that you have to define the site navigation only once.
Prerequisites
In order to complete this walkthrough, you will need the following:
Microsoft Visual Web Developer Web development tool.
The .NET Framework.
This walkthrough assumes that you know how to use Visual Web Developer.
Creating a Web Site That Has Example Pages and a Site Map
If you have already created a Web site in Visual Web Developer by completing
Walkthrough: Creating a Basic Web Page in Visual Web Developer, you can use that Web site and go to the next section.
Otherwise, create a new Web site and page by following these steps.
Creating a File System Web Site

To create a file system Web site


1. Open Visual Web Developer.
2. On the File menu, click New Web Site (or on the File menu, click New, and then click Web Site).
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the left-most Location box, click File System, and then in the right-most Location box, enter the name of the folder
where you want to keep the pages of the Web site.
For example, type the folder name C:\WebSites\SiteNavigation.
5. In the Language box, click the programming language that you prefer to work in.
The programming language that you choose will be the default for the Web site, but you can set the programming
language for each page individually.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating a Site Map
To use site navigation, you need a way to describe how the pages in your site are laid out. The default method is to create an
.xml file that contains the site hierarchy, including the page titles and URLs.
The structure of the .xml file reflects the structure of your site. Each page is represented as a siteMapNode element in the site
map. The top-most node represents the home page, and child nodes represent pages that are deeper in the site.
To create a site map
1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
2. In the Add New Item <Path> dialog box:
a. Under Visual Studio installed templates, click Site Map.
b. In the Name box, Make sure that the name is Web.sitemap.
Note
The file must be named Web.sitemap and must appear in the root of the Web site.

c. Click Add.
3. Copy the following XML content into the Web.sitemap file, overwriting the default contents.

<siteMap>
<siteMapNode title="Home" description="Home" url="~/home.aspx" >
<siteMapNode title="Products" description="Our products"
url="~/Products.aspx">
<siteMapNode title="Hardware"
description="Hardware we offer"
url="~/Hardware.aspx" />
<siteMapNode title="Software"
description="Software for sale"
url="~/Software.aspx" />
</siteMapNode>
<siteMapNode title="Services" description="Services we offer"
url="~/Services.aspx">
<siteMapNode title="Training" description="Training"
url="~/Training.aspx" />
<siteMapNode title="Consulting" description="Consulting"
url="~/Consulting.aspx" />
<siteMapNode title="Support" description="Support"
url="~/Support.aspx" />
</siteMapNode>
</siteMapNode>
</siteMap>

The Web.sitemap file contains a set of siteMapNode elements that are nested to three levels. The structure of each
element is the same. The only difference among them is the location within the XML hierarchy.
The URL of the pages that are defined in the sample .xml file is unqualified. This means that all pages are treated as
having URLs that are relative to the application root. However, you can specify any URL for a specific page — the logical
structure that you define in the site map does not have to correspond to the physical layout of the pages in folders.
4. Save the file, and then close it.
Creating Pages to Navigate
In this section, you will create only a few of the pages that are described in the site map that you defined in the preceding
section. (The site map is more complete so that you will be able to view a full hierarchy when testing the pages in this
walkthrough.)
To create pages to navigate
1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
2. In the Add New Item <Path> dialog box:
a. Under Visual Studio installed templates, click Web Form.
b. In the Name box, type Home.aspx, and then click Add.
3. Switch to Design view.
4. On the Home.aspx page, type Home, and then format it as a Heading 1.
Repeat this procedure and create four additional pages named Products.aspx, Hardware.aspx, Software.aspx, and
Training.aspx. Use the name of the page (for example, Products) as the heading so that you will be able to recognize
each page when the page is displayed in the browser.
It is not important which pages you specifically create. The pages that are listed in this procedure are suggestions that
will let you see the site hierarchy nested to three levels.
Creating a Navigation Menu Using the TreeView Control
Now that you have a site map and some pages, you can add navigation to your site. You will use the TreeView control to act
as a collapsible navigation menu.

To add a tree-style navigation menu


1. Open the Home.aspx page.
2. From the Data group in the Toolbox, drag a SiteMapDataSource control onto the page.
In its default configuration, the SiteMapDataSource control retrieves its information from the Web.sitemap file that you
created in "Creating a Site Map," earlier in this walkthrough, so that you do not have to specify any additional
information for the control.
3. From the Navigation group in the Toolbox, drag a TreeView control onto the page.
4. On the TreeView Tasks menu, in the Choose Data Source box, click SiteMapDataSource1.
5. Save the page.
Testing the Tree Style Navigation Menu
You can now perform an interim test of your navigation system.
To test the navigation menu
1. Press CTRL+F5 to run the Home.aspx page.
The tree shows two levels of nodes.
2. Click Products to view the Products page.
If you did not create a Products.aspx page, click the link for a page that you did create.
In the current state of the Web site, the navigation menu appears only on the Home page. You could add the same
SiteMapDataSource and TreeView controls to each page in the application to display a navigation menu on each page.
However, later in this walkthrough, you will see how to place the navigation menu on a master page so that the navigation
menu automatically appears with every page.
Displaying Navigation History Using the SiteMapPath Control
Besides creating a navigation menu by using the TreeView control, you can add navigation on each page that displays where
the page is in the current hierarchy. This kind of navigation control is also known as a breadcrumb. ASP.NET provides the
SiteMapPath control that can automatically implement page navigation.
To display navigation history
1. Open the Products.aspx page and switch to Design view.
2. From the Navigation group in the Toolbox, drag a SiteMapPath control onto the page, place the cursor in front of the
SiteMapPath control, and then press ENTER to create a new line.
The SiteMapPath control displays the position of the current page in the page hierarchy. By default, the SiteMapPath
control represents the hierarchy that is created in the Web.sitemap file. For example, when you display the Products.aspx
page, the SiteMapPath control displays the following path:
Home > Products
3. Repeat this procedure for the other pages that you have created in this walkthrough, except the Home page.
Even if you do not put a SiteMapPath control on each page, for testing purposes you need a control on a page at each
level of the site hierarchy (for example, on the Products.aspx and Hardware.aspx pages).
Testing Navigation History
You can test page navigation by viewing pages that are at the second and third levels of the hierarchy.
To test page navigation
1. Open the Home.aspx page, and then press CTRL+F5 to run the page.
2. Use the TreeView control to move to the Products page.
At the location in the page where you put the SiteMapPath control, you see a path that is similar to the following:
Home > Products
3. Click Home to return to the Home page.
4. Use the TreeView control to move to the Hardware page.
This time you see a path that is similar to the following:
Home > Products > Hardware
All page names that are displayed by the SiteMapPath control are links, except the last one, which represents the current
page. You can make the current node into a link by setting the RenderCurrentNodeAsLink property of the SiteMapPath
control to true.
The SiteMapPath control lets users move back up the site hierarchy, but it does not allow for them to jump to a page that is
not in the current hierarchy path.
Creating a Navigation Menu Using the Menu Control
Besides creating a navigation menu by using the TreeView control, you can use the Menu control to display an expandable
navigation menu that lets users view one level of nodes at a time. Pausing the mouse pointer over a node that has child nodes
generates a submenu of the child nodes.
To add a menu-style navigation menu
1. Open the Products.aspx page and switch to Design view.
2. From the Navigation group in the Toolbox, drag a Menu control onto the page.
3. On the Menu Tasks menu, in the Choose Data Source box, click NewDataSource.
4. In the Configure Data Source — <Datasourcename> wizard, click Site Map, and then click OK.
5. Save the page.
Testing the Menu Style Navigation Menu
You can now perform an interim test of your navigation system.
You can now perform an interim test of your navigation system.
To test the navigation menu
1. Close Menu Tasks.
2. Open the Home.aspx.
3. Press CTRL+F5 to run the Home.aspx page.
The tree shows two levels of nodes.
4. Click Products to view the Products page.
If you did not create a Products.aspx page, click the link for a page that you did create.
5. On the navigation menu, rest the mouse pointer on the Home link to expand the menu.
In the current state of the Web site, the navigation menu appears only on the Home page. You could add the same
SiteMapDataSource and Menu controls to each page in the application to display a navigation menu on each page. However,
in the next section of this walkthrough, you will see how to put the navigation menu on a master page so that it automatically
appears with each page.
Combining Site Navigation with Master Pages
In the pages that you have created up to this point in this walkthrough, you have added site navigation controls individually to
each page. Doing this is not especially complex, because you do not have to configure the controls differently for each page.
However, it can add to the maintenance costs for your site. For example, to change the location of the SiteMapPath control for
pages in your site, you would have to change each page individually.
By using site navigation controls in combination with master pages, you can create a layout that contains the navigation
controls in one location. You can then display pages as content within the master page.
To create the master page for navigation
1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
2. In the Add New Item <Path> dialog box:
a. Under Visual Studio installed templates, click Master Page.
b. In the Name box, type Navigation.master, and then click Add.
3. Switch to Design view.
The master page appears with a default ContentPlaceHolder control.
In the following procedure, you will create a master page with a simple layout for navigation controls. In a real application, you
would likely use more sophisticated formatting, but the techniques for using navigation controls on a master page will be
similar.
To add navigation controls to the master page
1. Click the title bar for the ContentPlaceHolder control, press LEFT ARROW, and then press SPACEBAR.
This inserts a blank line in front of the ContentPlaceHolder control.
2. From the Data group in the Toolbox, drag a SiteMapDataSource control onto the master page and position it above
the ContentPlaceHolder control.
Note
Do not position the SiteMapDataSource control on the ContentPlaceHolder control.

By default, the SiteMapDataSource control will use the Web.sitemap file that you created in "Creating a Site Map,"
earlier in this walkthrough.
3. Click the SiteMapDataSource control, press RIGHT ARROW, and then press SPACEBAR.
This inserts a blank line under the SiteMapDataSource control.
4. On the Layout menu, click Insert Table, and then insert a table that has one row, two columns, and a width of 100
percent.
5. From the Navigation group in the Toolbox, drag a TreeView control onto the left cell of the table.
6. On the TreeView Tasks menu, in the Choose Data Source box, click SiteMapDataSource1.
7. From the Navigation group in the Toolbox, drag a SiteMapPath control onto the right cell of the table.
8. In the right cell, click the blank area, and then press SHIFT+ENTER to create a new line.
9. Drag the ContentPlaceholder control onto the right cell of the table and position it under the SiteMapPath control.
When you are using a master page, you create the pages in your site as content pages. The content pages use Content
controls to define the text and controls that are displayed in the ContentPlaceholder control of the master page. Therefore,
you will have to re-create the Home, Products, and Hardware pages as content pages.
To create content pages for the site
1. In Solution Explorer, right-click the Home.aspx page, click Delete, and then click OK.
2. Repeat step 1 for the Products.aspx, Software.aspx, Training.aspx, and Hardware.aspx pages, and any other pages you
have created.
You will re-create the pages as content pages that use a master page.
3. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
4. In the Add New Item dialog box:
a. Under Visual Studio installed templates, click Web Form.
b. In the Name box, type Home.aspx.
c. Select the Select master page check box.
d. Click Add.
The Select a Master Page dialog box appears.
5. Under Contents of folder, click Navigation.master, and then click OK.
You have created a content page that is bound to the master page that you created in the preceding section.
6. Switch to Design view.
In Design view, you see the layout that you created for the master page, with an editable region in a Content1 control
corresponding to the ContentPlaceHolder1 control on the master page.
7. Click inside the Content window.
This is where you can add content for this specific page.
8. Type Home, and then format the text as Heading 1.
You have created the static text (specifically, the heading) for the Home page.
9. Repeat steps 3 through 8 to create a Products.aspx content page and a Hardware.aspx content page. In step 8, type
Products and Hardware, respectively, instead of Home.
Testing Navigation Controls in the Master Page
Testing with master pages and content pages is the same as testing individual pages.
To test navigation controls in the master page
1. Open the Products.aspx page, and then press CTRL+F5 to run the page.
The Products content page is merged with the master page. In the browser, you see a page that contains the Products
heading and the navigation controls that you added to the master page.
2. In the TreeView control, click Hardware.
The Hardware page is displayed with the same layout as the Products page, except that the SiteMapPath control
displays a different path.
Next Steps
This walkthrough illustrates the basic functionality of ASP.NET site navigation and the navigation controls. You might want to
experiment with additional features of navigation. For example, you might want to do the following:
Format the SiteMapPath control to customize its appearance. The control supports many options that manage how the
links are displayed. For more information, see SiteMapPath.
Customize the display of the pages in the TreeView control. For example, you might highlight the current page in the tree
view node.
Work programmatically with the site-navigation information. A SiteMapPath control is available on the current page,
which you can use to programmatically display navigation information.
Use a different data store for the site-map information. Instead of using the default XML site-map file, you might want to
use an existing site map or store site-map information in a database. ASP.NET site navigation uses a provider model. You
can create a component that manages site-map information, and then configure your application to use that component
instead of the default site-map provider. For more information, see ASP.NET Site Navigation Providers.
See Also
Tasks
Walkthrough: Creating a Basic Web Page in Visual Web Developer
Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer
Concepts
ASP.NET Site Navigation Overview
ASP.NET Site Maps
ASP.NET Master Pages Overview
Securing ASP.NET Site Navigation
Securing Data Access
Basic Security Practices for Web Applications (Visual Studio)
Other Resources
ASP.NET Application Security in Hosted Environments
Visual Web Developer

Walkthrough: Creating a Web Site with Membership and User


Login (Visual Studio)
A common requirement for Web sites is to allow only some members or other authenticated users to see certain pages. In that
case, the application must prompt the user for a name and password. The application must also include a way to hide
information from anonymous users (users who are not logged in). This walkthrough shows you how to use ASP.NET controls
and ASP.NET membership services to create an application that performs all these tasks. For more information, see
Introduction to Membership.
Tasks illustrated in this walkthrough include:
Configuring an application to include ASP.NET membership services, and how to define users.
Using login controls to get user credentials and to display information to logged-in users.
Protecting one or more pages in your application so that only logged-in users can view them.
Allowing new users to register at your site.
Allowing members to change and reset their passwords.
Prerequisites
In order to complete this walkthrough, you will need:
Microsoft Visual Web Developer.
Microsoft Internet Information Services (IIS) installed locally on your computer.
Microsoft Data Access Components (MDAC) version 2.7 or later. If you are using Microsoft Windows XP or Windows
Server 2003, you already have MDAC 2.7. However, if you are using Microsoft Windows 2000, you might to need to
upgrade the MDAC already installed on your computer. For more information, see the article "Microsoft Data Access
Components (MDAC) Installation" in the MSDN library.
Access to an e-mail server that can forward e-mail messages. (The server does not have to be able to receive messages.)
IIS includes the Default SMTP virtual server, a mail server that is suitable for this walkthrough. For more information
about configuring this server, see How to: Install and Configure SMTP Virtual Servers in IIS. If you are working on a local
area network, check with your network administrator for information about access to an e-mail server.
Creating the Web Site
If you have already created a Web site in Microsoft Visual Studio (for example, by working with the topic
Walkthrough: Creating a Basic Web Page in Visual Web Developer ), you can use that Web site and skip to "Configuring
Membership" later in this walkthrough. Otherwise, create a new Web site and page by following these steps.
To create a local IIS Web site
1. Open Visual Studio.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, select ASP.NET Web Site.
4. In the Location list box, select HTTP. Click Browse.
The Choose Location dialog box appears.
5. Select Local IIS.
6. Open Local Web Servers.
7. Select Default Web Site.
8. Click the Create New Web Application icon ( ) above the list of Web sites and then name the new Web site
membership.
9. Click Open.
The Choose Location dialog box closes.
10. In the Languages box, click the programming language you prefer to work in.
The programming language you choose will be the default for your Web site, but you can set the programming
languages for each page individually.
11. Click OK in the New Web Site dialog box.
Visual Web Developer creates the Web site and a new page named Default.aspx.
Configuring Membership
Later in this walkthrough you will put pages into a subdirectory that is protected. You must create the subdirectory now so that
you can configure security for it later in the walkthrough.
To add a new folder to the Web site
1. In Solution Explorer, right-click the name of your Web site and click New Folder.
2. Name the folder MemberPages.
Before you work with ASP.NET membership, you must configure your application to enable membership and to set up users.
You can use the Web Site Administration tool, which provides a wizard-like interface for making configuration settings.
For this walkthrough, you will define a single user.
To create a membership user
1. On the Website menu, click ASP.NET Configuration.
2. Select the Security tab, click the link to Use the security Setup Wizard to configure security step by step, and then
click Next.
3. Proceed to Step 2 of the wizard and select the From the Internet option.
The wizard displays a page where you can select the authentication method that your Web site will use. This option
specifies that your application will use Forms authentication, where users will log in to the application using a login page
that you will create later in this walkthrough.
4. Click Next.
The wizard displays a message stating that user information will be stored using Advanced provider settings. By
default, membership information is stored in a Microsoft SQL Server Express database file in the App_Data folder of
your Web site.
5. Click Next.
The wizard displays an option to create roles. You will perform this step separately later in the walkthrough. Therefore, do
not select the Enable roles for this web site check box.
6. Click Next.
The wizard displays a page where you can create new users.
7. Enter information that defines a user of your application. Use the following values as guidelines (you can use any values
that you like, but be sure to note your entries for later in the walkthrough):
User Name Your name (with no spaces), or a sample name.
Password A password. A strong password is required (one that includes uppercase and lowercase letters,
punctuation, and that is at least eight characters long).
E-mail Your personal e-mail address. Later in the walkthrough you will send yourself an e-mail message, so you
need a legitimate e-mail address.
Security Question and Security Answer Type a question and answer that can be used later if you need to
recover your password.
8. Click Create User.
The wizard displays a confirmation page.
Note
Leave the Web Site Administration tool open.

Earlier in the walkthrough you created a folder named MemberPages. In this part of the walkthrough, you will create a rule
that makes sure that only logged-in users can access pages in that folder.
To set up access rules for the MemberPages subdirectory
1. In the wizard, click Next.
The wizard displays a page that allows you to create access rules.
2. In the Add New Access Rule box, expand the node for your Web site.
3. Select MemberPages, the folder you created earlier.
4. Under Rule applies to, select Anonymous users.
5. Under Permission, select Deny.
The rule you are creating denies access to anonymous users — that is, users who have not logged in.
6. Click Add This Rule.
The new rule is displayed in the grid below. When users request a page from the MemberPages subdirectory, the rules
are checked to determine whether the user is allowed access to the page.
7. Click Finish.
You are now done with the wizard. The wizard closes and you are returned to the Security tab of the Web Site
Administration tool.
Configuring the Application for E-Mail
For part of this walkthrough, the application needs to be able to send e-mail messages. To send messages, your application
must have access to a Simple Mail Transport Protocol (SMTP) server, which forwards e-mail messages from your application to
an e-mail recipient.
IIS includes the Default SMTP virtual server as an optional component, which is suitable for this walkthrough. For more
information about configuring this server, see How to: Install and Configure SMTP Virtual Servers in IIS. If you are working on a
local area network, check with your network administrator for information about access to an e-mail server.
After you have set up or determined how to access an SMTP server, you must configure your application to route e-mail
messages to that server. You can do so by making an entry in your Web site's Web.config file, which contains a series of
settings that determine how your application runs.
To configure the application to use a specific SMTP server
1. In the Web Site Administration tool, click the Application tab.
2. Under SMTP Settings, click Configure SMTP e-mail settings.
The tool displays a page where you can configure e-mail.
3. If you are using the SMTP virtual server that is on your computer, enter localhost as the Server Name; otherwise, enter
the appropriate server name.
Include information for the port number and for authentication according to the requirements of your SMTP server. See
your administrator for more information on how to configure these settings.
4. In the From box, type a valid e-mail address.
5. Click Save, and in the confirmation page, click OK.
The Web Site Administration tool creates a Web.config file (if one did not already exist) with the settings you have made.
Note
The Web.config file will not appear in Solution Explorer until you refresh the view.

6. Close the Web Site Administration tool.


Logging the User In
As part of your application, you need to establish the user's identity so that the application can perform actions — such as
showing or hiding information — based on who the user is. To get the user's identity, you have the user log in.
In this walkthrough, you will add a link on the home page that takes users to a login page, and then you will create the login
page.
To create a home page with a login button
1. Open or switch to the Default.aspx page of your site. (If you do not have a Default.aspx page, you can add one or use a
different page.)
2. Switch to Design view.
3. Type static text such as Welcome to our site and, in the Formatting toolbar, use the Block Format drop-down list to
format the text as Heading 1.
4. From the Login group of the Toolbox, drag a LoginStatus control onto the page.
By default, the LoginStatus control is rendered as a link. When users click it, the application displays a login page. You can
now create the login page.
To create a login page
1. In Solution Explorer, right-click your Web application and select Add New Item. Add a Web Form named Login.aspx
to your site.
Note
For this walkthrough, the page must be named Login.aspx. By default, forms authentication is configured to work with
a page with this name. Although you will not do so in this walkthrough, you can change the default login page — the p
age to which users are redirected — in the Web.config file.

2. In the Login.aspx page, switch to Design view.


3. From the Login group of the Toolbox, drag a Login control onto the page.
The Login control is a single control that will prompt the user for credentials and validate them.
Displaying Login Errors
The Login control includes validation to help users enter correct information. For example, if a user skips the password, a
validator control displays an asterisk (*) next to the Password box. You can provide more complete information for login
errors by adding a ValidationSummary control to the page.
To display detailed login errors
1. From the Validation group of the Toolbox, drag a ValidationSummary control onto the page.
2. In the Properties window for the ValidationSummary control, set the ValidationGroup property to Login1, which is
the default ID of the Login control you added previously.
Displaying Information for Logged-In Users
You will now modify the home page to customize the display depending on whether the user is logged in. Anonymous users
will see a generic message inviting them to log in. Logged-in users will see a message that welcomes them by their logged-in
name.
To customize the display for logged-in users
1. Switch to or open the Default.aspx page.
2. From the Login group of the Toolbox, drag a LoginView control onto the page.
The LoginView control is displayed with its AnonymousTemplate template open. This template allows you to define
the content that users will see before they have logged in.
3. Click the edit area of the LoginView control to activate editing.
4. In the edit area of the LoginView control's AnonymousTemplate template, type You are not logged in. Click the
Login link to sign in.
5. On the LoginView Tasks panel, in the Views list, click LoggedInTemplate. If you do not see the LoginView Tasks
panel, right-click the heading of the LoginView control and select Show Smart Tag.
You are now defining the content that will be displayed to users who have already logged in.
6. Click the edit area of the LoginView control to activate editing, and then type You are logged in. Welcome,.
7. From the Login group of the Toolbox, drag a LoginName control into the template after the text.
Testing Login
You can now test the login capability of your application.
To test login
1. In Solution Explorer, right-click Default.aspx and click Set As Start Page.
This configures the Web site so that when you run the site, the Default.aspx page appears first.
2. Press CTRL+F5 to run the Web site.
The home page (Default.aspx) appears in the browser, showing the Login link and the generic message.
3. Click the Login link.
The login page you created is displayed.
4. Type the login name of the user you created earlier in the walkthrough, and then click Log In. (Do not yet enter a
password.)
An asterisk (*) is displayed next to the Password box, and an error message is displayed in the ValidationSummary
control.
5. Type both a user name and password and then click Log In.
If you entered correct credentials, you are returned to the home page. The page now displays a Logout link, your user
name, and the welcome message that you defined for the logged-in user.
6. Close the browser.
Limiting Access for Members-Only Pages
A typical task in many Web sites is to configure pages so that only logged-in users can view the pages. Earlier in the
walkthrough, you created the MemberPages subdirectory and created a rule that limits access to pages in the subdirectory. In
this section of the walkthrough, you will add a page to the protected subdirectory and test the access rule.
To create the members-only page
1. In Solution Explorer, right-click the MemberPages folder, click Add New Item, and add a new Web Form named
Members.aspx.
Note
Be sure to create the page in the MemberPages folder.

2. In Design view, add text to the page, such as Welcome, members! The exact text does not matter, as long as you will be
able to recognize this page when you see it in the browser.
You can now add a link to the members-only page from the home page. In a real application, you would probably put the
members-only page link in the logged-in template of the LoginView control. That way, visitors to your site would not see the
link until they were logged in. For this walkthrough, however, you will make the link available to all users so that you can see
the effect of trying to view a members-only page without first logging in.
To add a link to the members-only page
1. Switch to or open the Default.aspx page.
2. From the Standard group of the Toolbox, drag a HyperLink control onto the page.
3. In the Properties window for the HyperLink control, set the Text property to Members page and the NavigateUrl
property to ~/MemberPages/Members.aspx to point to the page that you created previously.
Testing the Members-Only Page
You can test the members-only page by accessing it both as an anonymous user and a logged-in user.
To test the members-only page
1. Press CTRL+F5 to run the Web site.
2. When the Default.aspx page appears in the browser, do not log in. Instead, click the Members page link.
You are redirected to the Login.aspx page because access to the members page is denied for anonymous users.
3. In the login page, type the user name and password that you used earlier in the walkthrough to log in.
You are redirected to the Members.aspx page because the user name you are logged in as has been authorized to access
the page.
4. Close the browser window.
Creating New Users
In the first part of the walkthrough, you created a user with the Web Site Administration tool. That strategy is useful if you are
working with a small, defined list of users; for example, if you are creating users for a small team. In many Web sites, however,
users are allowed to register themselves. ASP.NET includes the CreateUserWizard control that performs the same task you
performed earlier using the Web Site Administration tool.
In this part of the walkthrough, you will add a facility that allows users to register on your Web site. To start, you will create a
registration page.
To create a registration page
1. In Solution Explorer, right-click the name of your Web site, click Add New Item, and add a new Web Form named
Register.aspx.
Note
Be sure to create the page in the root of the Web site, not in the MemberPages folder.

2. In the Register.aspx page, switch to Design view and type static text such as Register into the page. In the Formatting
toolbar, use the Block Format drop-down list to format the text as Heading 1.
3. From the Login group of the Toolbox, drag a CreateUserWizard control onto the page.
4. In the Properties window for the CreateUserWizard control, set the ContinueDestinationPageUrl property to
~/Default.aspx.
This configures the control so that when users click Continue after creating a user, the control returns to the home page.
5. From the Standard group of the Toolbox, drag a HyperLink control onto the page. In the Properties window for the
HyperLink control, set the Text property to Home and the NavigateUrl property to ~/Default.aspx.
You can now add a link to the home page that displays the registration page. For this walkthrough, assume that you want to
display the registration link only to users who are not logged in.
To create a registration link on the home page
1. Switch to or open the Default.aspx page.
2. Right-click the LoginView control added previously, and select Show Smart Tag. In the LoginView Tasks panel, select
AnonymousTemplate from the Views list box to activate editing in the anonymous template.
3. From the Standard group of the Toolbox, drag a HyperLink control into the anonymous template. In the Properties
window for the HyperLink control, set the Text property to Register and the NavigateUrl property to Register.aspx.
The Register link will be displayed only to users who are not logged in.
You can now test the registration process.
To test registration
1. Press CTRL+F5 to run the Web site and display the Default.aspx page.
Because you are not logged in, the page containing the Register link is displayed.
2. Click the Register link.
The registration page is displayed.
3. In the text boxes, enter a new user name, a strong password, an e-mail address, and a security question and answer. (All
five pieces of information are required.)
4. Click Create User.
A confirmation message is displayed.
5. Click the Continue button.
You are returned to the home page as a logged-in user. Note that the Login link has changed to Logout and that the
information displayed in the Login control is from the LoggedInTemplate property, not from the AnonymousTemplate
property.
6. Click the Logout link.
The page changes to display the information for anonymous users.
7. Click the Login link.
8. Enter the credentials for the user you just created.
You are logged in as the new user.
9. Close the browser window.
Changing Passwords
Users sometimes might want to change their passwords, and it is often impractical to perform this task by hand. You can
therefore use another ASP.NET control to allow users to change passwords on their own. To change a password, users must
know their existing password.
In this walkthrough, you will add a page where logged-in users can change their password.
To create a password-change page
1. In Solution Explorer, right-click the MemberPages folder, click Add New Item, and add a new Web Form named
ChangePassword.aspx.
Note
Be sure to create the page in the MemberPages folder.

You are putting the page in the members-only folder because only logged-in users can change their passwords.
2. In the ChangePassword.aspx page, switch to Design view and type static text such as Change Password. In the
Formatting toolbar, use the Block Format drop-down list to format the text as Heading 1.
3. From the Login group of the Toolbox, drag a ChangePassword control onto the page.
4. In the Properties window for the ChangePassword control, set ContinueDestinationPageUrl property to
~/Default.aspx.
5. This configures the control so that when users click Continue after changing a password, the control returns to the
home page.
You can now add a link to the home page that displays the password-change page. You will make the link available only to
users who are logged in.
To create a password-change link on the home page
1. Switch to or open the Default.aspx page.
2. Right-click the LoginView control and then click Show Smart Tag. In the LoginView Tasks menu, in the Views list,
click LoggedInTemplate.
This switches the LoginView control to edit mode for the content that will appear to users who are logged in.
3. From the Standard group of the Toolbox, drag a HyperLink control into the editing region. In the Properties window
for the HyperLink control, set the Text property to Change password and the NavigateUrl property to
~/MemberPages/ChangePassword.aspx.
The Change password link will be displayed only to users who are logged in, which is the opposite of the Register link
you created earlier.
You can now test the password-change process.
To test password change
1. Press CTRL+F5 to run the Web site.
2. In the Default.aspx, page, click the Login link and log in as one of the users you have created.
When you are finished, you are returned to the home page as a logged-in user.
3. Click the Change password link.
4. In the password-change page, enter the old password and a new password, and then click Change Password.
5. Click Continue.
6. On the home page, click Logout.
7. Click the Login link.
8. Enter the new password.
You are logged in with the new password.
9. Close the browser window.
Recovering a Password
Users will occasionally forget their passwords. You can add a password recovery page to your Web site so that they can once
again log in to your site. Password recovery can take two forms:
You can send users the password they selected (or that you created for them when you set up the site). This option
requires that the site store the password using reversible encryption.
You can send users a new password, which they can change using the Change Password page you created earlier. This
option is useful if the Web site stores passwords using a non-reversible encryption scheme such as hashing.
Note
Returning a password in clear text using e-mail is not recommended for sites that require a high level of security. For high-se
curity sites, it is recommended that you return passwords using encryption, such as Secure Sockets Layer (SSL).
By default, the ASP.NET membership system secures passwords by hashing them, meaning that the passwords cannot be
recovered. Therefore, for this part of the walkthrough, your Web site will send users a new password.
Note
Password recovery requires that your Web site can send e-mail messages. If you are not able to configure your Web site to s
end e-mail (as explained under "Configuring the Application for E-Mail" earlier in this walkthrough), you will not be able to a
dd password recovery to your site.

To add password recovery


1. In Solution Explorer, right-click the name of your Web site, click Add New Item, and add a new Web Form named
RecoverPassword.aspx.
Note
Be sure to create the page in the root of the Web site, not in the MemberPages folder.

2. In the RecoverPassword.aspx page, switch to Design view and type static text such as Reset my password to a new
value. In the Formatting toolbar, use the Block Format drop-down list to format the text as Heading 1.
3. From the Login group of the Toolbox, drag a PasswordRecovery control onto the page.
4. From the Standard group of the Toolbox, drag a HyperLink control onto the page. In the Properties window for the
HyperLink control, set the Text property to Home and the NavigateUrl property to ~/Default.aspx.
5. Switch to the Default.aspx page.
6. Right-click the LoginView control and then click Show Smart Tag. In the LoginView Tasks menu, in the Views list,
click AnonymousTemplate.
This switches the LoginView control to edit mode for the content that will appear to users who are not logged in.
7. From the Standard group of the Toolbox, drag a HyperLink control into the template. In the Properties window for
the HyperLink control, set the Text property to Forgot your password? and the NavigateUrl property to
~/RecoverPassword.aspx.
Now you can test password recovery.
To test password recovery
1. Press CTRL+F5 to run the Web site.
2. By default, you are not logged in, so you see the anonymous template of the LoginView control.
3. Click the Forgot your password? link.
The RecoverPassword.aspx page appears.
4. Type your user name and click Submit.
The security question is displayed and you are prompted to type the security answer.
5. Type the answer and click Submit.
If you entered a correct answer, the Web site resets your password and sends you an e-mail message with the new
password.
Next Steps
This walkthrough has illustrated a simple but complete scenario for creating an application that prompts users for credentials,
displays information to logged-in users, allows users to recover a forgotten password, and limits access to pages. You can
create more sophisticated pages and applications using the techniques and controls illustrated in the walkthrough. For
example, you might want to:
Create additional users and define roles (groups) such as managers, sales, or members and assign users to different
roles. For details, see Walkthrough: Managing Web Site Users with Roles.
Change the membership provider from the default Access provider to a SQL provider. Storing membership information
in an Access database is suitable for small to medium-sized sites, but if your site will experience heavy traffic, you will
want to use Microsoft SQL Server as the membership store. For more information, see
Web Site Administration Tool Provider Tab and Creating the Application Services Database for SQL Server.
Change the appearance of login controls. The Login, PasswordRecovery, and CreateUserWizard controls all support
templates, which allows you to configure the text and buttons they contain as well as change the color, font, and other
appearance characteristics of the controls. For more information, see the topics in the Login ASP.NET Controls section.
Create rules that limit access to pages or folders not only for anonymous users, but for specific users or roles.
Combine membership with profile properties, which allows you to store user-specific settings for each user. For details,
see Walkthrough: Maintaining Web Site User Information with Profile Properties.
Combine login controls with master pages. Master pages allow you to define a page layout that you can use for all the
pages in your application. For details, see
Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer.
Add the ability to recover a forgotten password. For more information, see
How to: Enable User Password Recovery Using the ASP.NET PasswordRecovery Control.
See Also
Concepts
Introduction to Membership
Visual Web Developer

Walkthrough: Maintaining Web Site User Information with


Profile Properties
ASP.NET Profile properties allow your application to track and permanently store user-specific information. For example, users
can specify a postal code or a favorite color scheme, and your application can store that information and retrieve it from
anywhere in the application. ASP.NET automatically matches the current user — whether the user is anonymous or logged on
— with the personal information that is stored for their user account.
This walkthrough shows you how to add Profile properties to your application and use the Profile properties to create a
personalized experience for visitors to the Web site.
During this walkthrough, you will learn how to do the following:
Configure an application to use Profile properties.
Define simple and complex Profile properties that you want to maintain for users.
Set and retrieve Profile values in your application.
Use Profile properties that have both anonymous and logged-on users.
Prerequisites
In order to complete this walkthrough, you will need the following:
Microsoft Visual Web Developer.
The Microsoft .NET Framework.
Microsoft SQL Server Standard Edition.
The Profile property information that you create in the walkthrough will be stored in a SQL Server Standard Edition
database.
Cookies enabled on your browser.
Note
ASP.NET Profile properties can work without cookies, if the application is configured to work without cookies. Howeve
r, for this walkthrough you will use the default configuration settings for Profile properties, which use cookies.

Creating and Configuring the Web Site


If you have already created a Web site in Microsoft Visual Studio by completing
Walkthrough: Creating a Basic Web Page in Visual Web Developer, you can use that Web site and go to the next section.
Otherwise, create a new Web site by following these steps.
To create a file system Web site
1. Open Visual Studio.
2. On the File menu, point to New, and then click Web Site (or on the File menu, click New Web Site).
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the left-most Location list, click File System.
5. In the right-most Location list, enter the name of the folder where you want to keep the pages of the Web site.
For example, type the folder name C:\WebSites.
6. In the Language list, click the programming language that you prefer to work in.
7. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Configuring Profile Properties
Before you work with ASP.NET Profile properties, you will configure your application to enable and define the Profile
properties that you want to track for each user. To start, you will create a single PostalCode property that the Web site will
track for users. You will also configure the PostalCode property so that your site can track it for both anonymous and logged-
on users.
You will first work as an anonymous user. Behind the scenes, ASP.NET will assign you a unique, anonymous ID that is stored in
a cookie on the computer. ASP.NET can use this anonymous ID to set and get values that are unique to you.
To configure Profile properties in the Web site
1. In Solution Explorer, determine whether the Web site already has a Web.config file.
If the Web site does not have a Web.config file, follow these steps:
a. Right-click the name of the Web site.
b. Click Add New Item.
c. Under Visual Studio installed templates, click Web Configuration File.
d. Click Add.
A new file named Web.config is added to the site and is opened in the editor.
2. Add the following <profile> element to the Web.config file as a child of the <system.web> element:

<system.web>

<anonymousIdentification enabled="true" />


<profile>
<properties>
<add name="PostalCode"
type="System.String"
allowAnonymous="true" />
</properties>
</profile>

<!-- other Web.config settings here -->


</system.web>

Note
Elements in the Web.config file are case sensitive. Therefore, make sure that you copy or type the elements exactly as s
hown.

You have added the following elements:


The <anonymousIdentification> element, which specifies whether Profile properties work only with logged-on
(authenticated) users or with both logged-on and anonymous users.
In this case, you have set enabled to true. Therefore, Profile property information will be tracked for both logged-
on and anonymous users.
The <properties> element, which contains all Profile properties that you are defining.
The <add> element, which defines a new <profile> element.
In this case, you have defined a single Profile property named PostalCode.
When you define a Profile property, you specify its data type using a .NET Framework–type class name. You also
specify whether the Profile property will be tracked for anonymous users. After enabling anonymous
identification, you can additionally specify whether to track Profile properties individually for anonymous users.
You would create a new add element for each additional Profile property that you wanted to define.
Note
By default, user profile information is stored in a SQL Server Standard Edition database in the Application_Data s
ubdirectory of the Web site. This walkthrough uses the default configuration. In production applications that will s
upport a significant number of users, it is better to store Profile property data in a Microsoft SQL Server databas
e. For more information, see "Next Steps," later in this walkthrough.

Setting and Getting the PostalCode Property


After you have configured the Web site to track a Profile property, you can set and get the Profile property as you would
ordinary component properties. In this section, you will create a page that shows how to set and get the PostalCode value that
you defined in the preceding section.
To create a page to set and get the PostalCode property
1. Add a new Web page to your site named Profiles.aspx.
2. Open Profiles.aspx and switch to Design view.
3. From the Standard group in the Toolbox, drag the controls listed in the following table onto the page, and then set their
properties as noted.
Control Property settings
TextBox ID = textPostalCode

Button ID = SetPostalCode
Text = Set Postal Code

Label ID = labelPostalCode
Text = (empty)

4. Switch to Source view, and then add the following attribute to the SetPostalCode button, if the attribute does not exist.

OnClick="SetPostalCode_Click"

5. Create a Click handler for Set Postal Code, and then add the following highlighted code.
VB
Sub SetPostalCode_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Profile.PostalCode = Server.HtmlEncode(textPostalCode.Text)
labelPostalCode.Text = Profile.PostalCode
End Sub

C#
void SetPostalCode_Click(object sender, System.EventArgs e)
{
Profile.PostalCode = Server.HtmlEncode(textPostalCode.Text);
labelPostalCode.Text = Profile.PostalCode;
}

When the user profile is enabled, ASP.NET dynamically creates a property named Profile that adds the user profile to the
current context. The individual Profile properties are then available through Profile.PostalCode.
6. Create a Page_Load handler, and then add the following highlighted code.
VB
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
labelPostalCode.Text = Profile.PostalCode
End Sub

C#
void Page_Load(object sender, System.EventArgs e)
{
labelPostalCode.Text = Profile.PostalCode;
}

This code will display the Profile.PostalCode value every time that the page is requested.
Testing the PostalCode Profile Property
You can now test the PostalCode property that you defined in the preceding section.
Note
If you are working with an existing Web site that has membership enabled, make sure that you are logged off.

To test the PostalCode property


1. Press CTRL+F5 to run the Profiles.aspx page.
Note
If the browser displays a 502 error or an error indicating that the page cannot be displayed, you might need to configur
e your browser to bypass proxy servers for local requests. For detailed information, see
How to: Bypass a Proxy Server for Local Web Requests.

2. In the box, type a postal code, and then click Set Postal Code.
The postal code that you entered appears in the Label control.
3. Close the browser to close your current session.
4. Reopen the browser, and then request the Profiles.aspx page.
The postal code that you entered earlier appears in the Label control.
The last step in the preceding procedure illustrated that ASP.NET store the PostalCode value. When you visit the page again,
ASP.NET can read the PostalCode value based on your unique anonymous ID.
Defining Complex Properties
In "Setting and Getting the PostalCode Property," earlier in this walkthrough, you created a simple property named
PostalCode that was stored as a string. In this section, you will define a property named FavoriteURLs that is a collection.
ASP.NET can store Profile properties of any type, but you must provide additional information when you are defining the
Profile property.
To define the FavoriteURLs property
1. Open the Web.config file.
2. Add the following highlighted element to the profile element that you created in "Configuring Profile Properties," earlier
in this walkthrough:

<anonymousIdentification enabled="true" />


<profile>
<properties>
<add name="PostalCode"
type="System.String"
allowAnonymous="true" />
<add name="FavoriteURLs"
type="System.Collections.Specialized.StringCollection"
allowAnonymous="true" />
</properties>
</profile>

You have added a new Profile property named FavoriteURLs. For Profile properties that are not simple types (such as
string or integer), you must specify the fully qualified type. Here, you are specifying that the Profile property will be a
collection that will hold strings.
3. Save, and then close the Web.config file.
Setting and Getting the FavoriteURLs Property
Working with the FavoriteURLs property, which is a collection, is much like working with a collection in any context. In this
part of the walkthrough, you will update the Profiles.aspx page that you created in "Setting and Getting the PostalCode
Property," earlier in this walkthrough, by adding a TextBox control in which users can type a URL. When the user clicks Add,
the URL is added to the FavoriteURLs property. You will also display the current list of favorite URLs in a drop-down list box.
To set and get the FavoriteURLs property
1. On the Profiles.aspx page, add the following controls and set their properties as noted in the following table.
Control Property settings
TextBox ID = textFavoriteURL

Button ID = AddURL
Text = Add URL

ListBox ID = listFavoriteURLs

2. Switch to Source view, and then add the following attribute to the Add URL button, if the attribute does not exist.

OnClick="AddURL_Click"

3. Create a Click handler for Add URL, and then add the following highlighted code.
VB
Sub AddURL_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Dim urlString As String = _
Server.HtmlEncode(textFavoriteURL.Text)
If Profile.FavoriteURLs Is Nothing Then
Profile.FavoriteURLs = New _
System.Collections.Specialized.StringCollection
End If
Profile.FavoriteURLs.Add(urlString)
DisplayFavoriteURLs()
End Sub

C#
void AddURL_Click(object sender, System.EventArgs e)
{
String urlString = Server.HtmlEncode(textFavoriteURL.Text);
if(Profile.FavoriteURLs == null)
{
Profile.FavoriteURLs = new
System.Collections.Specialized.StringCollection();
}
Profile.FavoriteURLs.Add(urlString);
DisplayFavoriteURLs();
}

4. In the Page_Load handler, add the following highlighted line of code.


VB
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
labelPostalCode.Text = Profile.PostalCode
DisplayFavoriteURLs()
End Sub

C#
void Page_Load(object sender, System.EventArgs e)
{
labelPostalCode.Text = Profile.PostalCode;
DisplayFavoriteURLs();
}

5. Add the following subroutine to update the display of the URLs in the ListBox control.
VB
Sub DisplayFavoriteURLs()
listFavoriteURLs.DataSource = Profile.FavoriteURLs
listFavoriteURLs.DataBind()
End Sub

C#
void DisplayFavoriteURLs()
{
listFavoriteURLs.DataSource = Profile.FavoriteURLs;
listFavoriteURLs.DataBind();
}

Testing the FavoriteURLs Profile Property


You can now test the FavoriteURLs property.
To test the FavoriteURLs property
1. To run the Profiles.aspx page, press CTRL+F5.
At first there are no values in the ListBox control.
2. In the box, type a URL, and then click Add.
The URL is added to the ListBox control.
3. Repeat the preceding step to add another URL.
4. Close the browser.
5. Reopen the browser, and then open the Profiles.aspx page.
Notice that the ListBox control is populated with the URLs that you entered before closing the browser.
Migrating Profile Properties During Log On
If a user first visits your site as an anonymous user, but then logs on, you might want to preserve the property settings that the
user established when anonymous. A typical example is a shopping site where the user might browse and add items to a
shopping cart as an anonymous user, but then log on to check out. To preserve a user's values when they log on, you migrate
the user from the current anonymous user profile to the user profile that they have as a logged-on user (authenticated).
In this section, you will migrate the user's PostalCode setting. You must have a Web site that is already configured to use user
identities and that has a logon page. If the Web site that you are working with has not already been configured for
membership, use the following procedure to enable it. If your site already supports membership, you can go to the next
section.
To configure the Web site for membership
1. In Visual Studio, on the Website menu, click ASP.NET Configuration.
The Web Site Administration Tool appears.
2. Click the Security tab.
3. Click Security, and then under Users, click Select authentication type.
4. Select From the internet, and then click Done.
The From the internet option specifies that your application will use Forms authentication, where users will log on to
the application by using a logon page.
5. On the Security tab, under Users, click Create user, and then create a user account.
You can use any name and password, but make sure that you remember the name and password. For the e-mail address,
use your own. (You will not be sending e-mail messages in this walkthrough.)
6. After finishing the user account definition, close the Web Site Administration Tool.
7. From the Login group in the Toolbox, drag a Login control and a LoginName control onto the page.
The LoginName control is not required for log on, but will help you see that you are logged on.
Creating a Migrating Handler
To migrate the settings for an anonymous user to the settings for a logged-on user, you must perform the migration when the
user's identity is changing. ASP.NET provides the MigrateAnonymous event for exactly this purpose; in the handler for the
MigrateAnonymous event, you can transfer the settings that you want to preserve.
To create a migration handler
1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
2. Under Visual Studio installed templates, click Global Application Class, and then click Add.
You do not have to enter a name, because the file is always named Global.asax.
3. Type the following code to create a new handler for the MigrateAnonymous event.
VB
Sub Profile_MigrateAnonymous(ByVal sender As Object, _
ByVal e As ProfileMigrateEventArgs)
If Profile.GetProfile(e.AnonymousID).PostalCode <> "" Then
Profile.PostalCode = _
Profile.GetProfile(e.AnonymousID).PostalCode
End If
End Sub
C#
void Profile_MigrateAnonymous(Object sender,
ProfileMigrateEventArgs e)
{
if(Profile.GetProfile(e.AnonymousID).PostalCode != String.Empty)
{
Profile.PostalCode =
Profile.GetProfile(e.AnonymousID).PostalCode;
}
}

The code gets the user profile for the anonymous user and extracts the PostalCode value. Then, it gets the profile for the
new user identity and sets the equivalent value for that identity.
Testing Migration
In order to test migration, you will first make some settings as an anonymous user. Then, you will log on and see that the
values are preserved.
To test migration
1. Open the Profiles.aspx page, and then press CTRL+F5 to run it.
The LoginName control does not display anything, because you have not yet logged on.
2. If a postal code is not displayed on the page, type a new postal code, and then click Set Postal Code.
The postal code for your current anonymous identity is displayed on the page.
3. Log on, using the user name and password that you created in "Migrating Profile Properties During Log On," earlier in
this walkthrough.
The LoginName control displays your user name. The postal code that you entered as an anonymous user is still
displayed, because the postal code settings have been migrated to your logged-on user profile.
Next Steps
This walkthrough has illustrated the basic procedures for configuring and using Profile properties in Web applications. You
can use Profile properties for many purposes in your applications. The following list suggests additional areas where you
might want to work with Profile properties:
Group Profile properties together, because it is easier to work with Profile properties as a unit.
For example, you can organize Profile properties named Street, City, and PostalCode into a group named Address.
For detailed information, see Defining ASP.NET Profile Properties.
Create custom types, such as a shopping cart, that you manage with Profile properties.
For detailed information, see Defining ASP.NET Profile Properties.
Select a different profile provider.
For this walkthrough, you stored Profile values in a SQL Server Standard Edition database. In production applications
that will support a significant number of users, it is better to store Profile property data in a SQL Server database that
uses the SqlProfileProvider class.
For more information, see Web Site Administration Tool Provider Tab and
Creating the Application Services Database for SQL Server.
Alternatively, you can create a custom profile provider that stores information in a format and storage medium that you
code yourself.
For detailed information, see Implementing a Profile Provider.
See Also
Concepts
ASP.NET Profile Properties Overview
ASP.NET Profile Providers
Visual Web Developer

Walkthrough: Customizing a Web Site Using Themes in Visual


Studio
This walkthrough illustrates how to use themes to apply a consistent look to pages and controls in your Web site. A theme can
include skin files that define a common look for individual controls, one or more style sheets, and common graphics for use
with controls, such as the TreeView control. This walkthrough shows you how to work with ASP.NET themes in your Web sites.
Tasks illustrated in this walkthrough include:
Applying predefined ASP.NET themes to individual pages and to your site as a whole.
Creating your own theme that includes skins, which are used to define the look of individual controls.
Prerequisites
In order to complete this walkthrough, you will need:
Microsoft Visual Web Developer (Visual Studio).
The .NET Framework.
Creating the Web Site
If you have already created a Web site in Visual Web Developer (for example, by following the steps in
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and go to the next section.
Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of your Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
To begin your work with themes in this walkthrough, you will set up a Button control, a Calendar control, and a Label control,
so you can see how these controls are affected by themes.
To place controls on the page
1. Switch to Design view.
2. From the Standard group of the Toolbox, drag a Calendar control, a Button control, and a Label control to the page.
The exact layout of the page is not important.
Note
Do not apply any formatting to any of the controls. For example, do not use the AutoFormat command to set the look
of the Calendar control.

3. Switch to Source view.


4. Be sure that the <head> element of the page has the runat="server" attribute so that it reads as follows:
<head runat="server"></head>

5. Save the page.


To test the page, you will want to see the page before a theme is applied, and then with different themes.
Creating and Applying a Theme to a Page
ASP.NET makes it easy to apply a predefined theme to a page, or to create a unique theme. (For details, see
How to: Define ASP.NET Themes.) In this part of the walkthrough, you will create a theme with some simple skins, which define
the appearance of controls.
To create a new theme
1. In Visual Web Developer, right-click the name of your Web site, click Add ASP.Net Folder, and then click Theme.
The folder named App_Themes and a subfolder named Theme1 are created.
2. Rename the Theme1 folder sampleTheme.
The name of this folder will be the name of the theme that you create (here, sampleTheme). The exact name is not
important, but you must remember it when you apply your custom theme.
3. Right click the sampleTheme folder, select Add New Item, add a new text file, and name it sampleTheme.skin.
4. In the sampleTheme.skin file, add skin definitions as shown in the following code example.

<asp:Label runat="server" ForeColor="red" Font-Size="14pt" Font-Names="Verdana" />


<asp:button runat="server" Borderstyle="Solid" Borderwidth="2px" Bordercolor="Blue" Ba
ckcolor="yellow"/>

Note
The exact characteristics that you define are not important. The values in the preceding selection are suggestions that w
ill be more obvious when you test the theme later.

The skin definitions are similar to the syntax for creating a control, except that the definitions include only settings that
affect the appearance of the control. For example, the skin definitions do not include a setting for the ID property.
5. Save the skin file, and then close it.
You can now test the page before any themes are applied.
Note
If you add a cascading style sheet (CSS) file to your sampleTheme folder, it will be applied to all pages that use the theme.

To test themes
1. Press CTRL+F5 to run the page.
The controls are displayed with their default appearance.
2. Close the browser, and then return to Visual Web Developer.
3. In Source view, add the following attribute to the @ Page directive:

<%@ Page Theme="sampleTheme" ... %>

Note
You must indicate the name of an actual theme in the attribute value (in this case, the sampleTheme.skin file you define
d previously).
4. Press CTRL+F5 to run the page again.
This time, the controls are rendered with the color scheme defined in your theme.
The Label and Button controls will appear with the settings you made in the sampleTheme.skin file. Because you did not
make an entry in the sampleTheme.skin file for the Calendar control, it is displayed with its default appearance.
5. In Visual Web Developer, set the theme to the name of another theme, if available.
6. Press CTRL+F5 run the page again.
The controls change appearance again.
Style Sheet Themes vs. Customization Themes
After you have created your theme, you can tailor how it is used in your application by associating it with your page as either a
customization theme (as done in the previous section), or as a style sheet theme. A style sheet theme uses the same theme files
as a customization theme, but its precedence within the page's controls and properties is lower, equivalent to a CSS file. Within
ASP.NET, the order of precedence is:
Theme settings, including themes set in your Web.config file.
Local page settings.
Style sheet theme settings.
In this regard, if you choose to use a style sheet theme, your theme's properties will be overridden by anything declared locally
within the page. Similarly, if you use a customization theme, your theme's properties will override anything within the local
page, and anything within any style sheet theme in use.
To use a style sheet theme and see order of precedence
1. Switch to Source view.
2. Change the page declaration:

<%@ Page theme="sampleTheme" %>

to a style sheet theme declaration:

<%@ Page StyleSheetTheme="sampleTheme" %>

3. Press CTRL+F5 to run the page.


Note that the ForeColor property of the Label1 control is red.
4. Switch to Design view.
5. Select Label1 and, in Properties, set ForeColor to blue.
6. Press CTRL+F5 to run the page.
The ForeColor property of Label1 is blue.
7. Switch to Source view.
8. Change the page declaration to declare a theme, rather than a style sheet theme, by changing:

<%@ Page StyleSheetTheme="sampleTheme" %>

back to:

<%@ Page Theme="sampleTheme" %>

9. Press CTRL+F5 to run the page.


The ForeColor property of Label1 is again red.
Basing a Custom Theme on Existing Controls
An easy way to create skin definitions is to use the designer to set appearance properties, and then copy the control definition
to a skin file.
To base a custom theme on existing controls
1. In Design view, set properties of the Calendar control so that the control has a distinctive look. The following settings are
suggestions:
BackColor Cyan
BorderColor Red
BorderWidth 4
CellSpacing 8
Font-Name Arial
Font-Size Large
SelectedDayStyle-BackColor Red
SelectedDayStyle-ForeColor Yellow
TodayDayStyle-BackColor Pink
Note
The exact characteristics that you define are not important. The values in the preceding list are suggestions that will be
more obvious when you test the theme later.

2. Switch to Source view and copy the <asp:calendar> element and its attributes.
3. Switch to or open the sampleTheme.skin file.
4. Paste the Calendar control definition into the sampleTheme.skin file.
5. Remove the ID property from the definition in the sampleTheme.skin file.
6. Save the sampleTheme.skin file.
7. Switch to the Default.aspx page, and drag a second Calendar control onto the page. Do not set any of its properties.
8. Run the Default.aspx page.
Both Calendar controls will appear the same. The first Calendar control reflects the explicit property settings that you
made. The second Calendar control inherited its appearance properties from the skin definition that you made in the
sampleTheme.skin file.
Applying Themes to a Web Site
You can apply a theme to an entire Web site, which means you do not need to reapply the theme to individual pages. (If you
want, you can override the themes settings on a page.)
To set a theme for a Web site
1. Create a Web.config file if one was not automatically added to your Web site by following these steps:
a. In Solution Explorer, right-click the name of your Web site, and then click Add New Item.
b. Under Templates, select Web Configuration File, and then click Add.
Note You do not need to type a name, because the file is always named Web.config.
2. Add the <pages> element if it does not already exist. The <pages> element should appear inside the <system.web>
element.
3. Add the following attribute to the <pages> element.

<pages theme="sampleTheme" />

Note
Web.config is case-sensitive and the values are camel-cased. (For example: theme and styleSheetTheme).

4. Save and close the Web.config file.


5. Switch to Default.aspx and switch to Source view.
6. Remove the theme="themeName" attribute from your page declaration.
7. Press CTRL+F5 to run Default.aspx.
The page is now displayed with the theme you specified in the Web.config file.
If you choose to specify a theme name in your page declaration, it will override any theme specified in your Web.config file.
Next Steps
ASP.NET support for themes gives you a variety of options for tailoring the look and feel of an entire application. This
walkthrough covered some of the basics, but you might be interested in learning more. For example, you might want to learn
more about:
Using themes in general. For more information, see ASP.NET Themes and Skins Overview
Creating your own themes and skins. For more information, see How to: Define ASP.NET Themes
Using themes with code. For more information, see How to: Apply ASP.NET Themes Programmatically
See Also
Concepts
ASP.NET Themes and Skins Overview
Visual Web Developer

Walkthrough: Displaying and Tracking Advertisements with


the AdRotator Control
Web sites frequently display advertisements or similar dynamic content that invites users to visit another site. ASP.NET
provides the AdRotator control, which simplifies this task. The AdRotator control displays a graphic representing an ad,
randomly selecting the ad from a list that you create. You can then track how frequently an ad is viewed and how frequently
users click it.
This walkthrough illustrates how to use the AdRotator control to display ads and provides a simple way to track ad responses.
Tasks illustrated in this walkthrough include the following:
Creating a list of ads to display.
Displaying ads on a page.
Creating a way to track the number of times an ad is clicked.
Displaying statistics about ad clicks.
Prerequisites
In order to complete this walkthrough, you will need the following:
Microsoft Visual Web Developer Web development tool.
The .NET Framework.
A general understanding of working in Visual Web Developer. For an introduction, see
Walkthrough: Creating a Basic Web Page in Visual Web Developer.
Creating the Web Site
If you have already created a Web site in Visual Web Developer by completing
Walkthrough: Creating a Basic Web Page in Visual Web Developer, you can use that Web site and go to the next section.
Otherwise, create a new Web site and page by following these steps.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, click File System, and then type the name of the folder where you want to keep the pages of the
Web site.
For example, type the folder name C:\WebSite.
5. In the Languages list, click the programming language that you prefer to work in.
The programming language that you choose will be the default for your Web site, but you can set the programming
language for each page individually.
6. Click OK.
Visual Studio creates the folder and a new page named Default.aspx.
Creating Advertisements
Ads are graphics that are displayed on the page with a target URL; when users click the graphic, they are redirected to the
target site. Therefore, you need graphics files to serve as advertisements.
Note
Later sections of this walkthrough assume that are you using graphics that are named according to the following procedure.
If you use existing graphics, make sure that you substitute the appropriate file names later in the walkthrough.

Start by creating a folder in the Web site to store graphics.


To create an Images folder
1. In Solution Explorer, right-click the name of the Web site, click New Folder, and then name the folder Images.
2. If you have existing graphics to use as ads, copy them to the new folder. Otherwise, follow the next procedure to create
some images.
If you already have some graphics that you can use to represent ads, you can use those. Otherwise, the following procedure
suggests one way that you can create graphics that are suited for this walkthrough.
To create graphics to serve as ads
1. In Microsoft Windows, open Paint.
2. On the Image menu, click Attributes.
3. In the Attributes dialog box, set Width to 250 and Height to 50, and then click OK.
4. From the Toolbox, drag the text tool onto the graphic, and then type some text that will help you identify the ad
5. In the <Websitename>\Images folder, save the graphic as <Websitename>\Images\Contoso_ad.gif.
6. Create a second graphic, and then save it as <Websitename>\Images\ASPNET_ad.gif.
7. Close Paint.
Creating a List of Ads
As soon as you have graphics for the ads, you must create a list of ads that the AdRotator control can read. The list is in the
form of an XML file.
To create an XML file of ads
1. In Solution Explorer, right-click App_Data, and then click Add New Item.
Note
When you put the XML file into the App_Data folder, the file automatically has the correct permissions to allow ASP.NE
T to read the file at run time. Putting the XML file in the App_Data folder helps to protect the file from being viewed in a
browser, because the App_Data folder is marked as nonbrowsable.

2. Under Visual Studio installed templates, click XML File.


3. In the Name box, type Sample.ads.
Note
Use the .ads extension.

4. Click Add.
A new XML file is created that contains only the XML directive.
5. Copy the following XML into the file, overwriting the XML directive.

<?xml version="1.0" encoding="utf-8" ?>


<Advertisements>
<Ad>
<ImageUrl>~/images/Contoso_ad.gif</ImageUrl>
<NavigateUrl>http://www.contoso.com</NavigateUrl>
<AlternateText>Ad for Contoso.com</AlternateText>
</Ad>
<Ad>
<ImageUrl>~/images/ASPNET_ad.gif</ImageUrl>
<NavigateUrl>http://www.asp.net</NavigateUrl>
<AlternateText>Ad for ASP.NET Web site</AlternateText>
</Ad>
</Advertisements>

Note
If your graphics files have different file names, change the names in the <ImageUrl> elements accordingly.

This XML file contains <Ad> elements for two advertisements corresponding to the two graphics files that you have
created. In a real application, the URLs in the <NavigateUrl> elements would refer to the advertisers' Web sites.
Note
Additional elements are available for defining ads. For detailed information, see AdvertisementFile.

6. Save the file, and then close it.


Displaying Ads on the Page
You will now configure a Web page to display the ads that you have created. In the following procedure, you will bind an
AdRotator control to an XmlDataSource control. However, when using a static XML file, a data source control is not required,
because the XML file can be set directly with the AdvertisementFile property of the AdRotator control.
To display ads on the page
1. If you created a new Web site for this walkthrough, open the Default.aspx page.
2. If you are using a Web site that existed before you started this walkthrough, add a new page by following these steps:
a. In Solution Explorer, right-click the name of the Web site (for example, C:\WebSites), and then click Add New Item.
b. Under Visual Studio installed templates, click Web Form.
c. In the Name box, type TestAds.aspx.
d. Click Add.
3. Open TestAds.aspx and switch to Design view.
4. From the Standard group in the Toolbox, drag an AdRotator control onto the page.
The AdRotator Tasks shortcut menu appears.
5. In the Choose Data Source list, click New data source.
The Data Source Configuration wizard appears.
6. Under Where will the application get data from, click XML File.
7. In the Specify an ID for the data source box, leave the default, (XmlDataSource1).
8. Click OK.
The Configure Data Source dialog box appears.
9. In the Data file box, enter ~/App_Data/Sample.ads, and then click OK.
Alternatively, you can use Browse to locate the file:
a. In the Select XML File dialog box, in the Files of type list, click All Files (*.*).
b. Under Project Folders, click App_Data.
c. Under Contents of Folder, click Sample.ads, click OK, and then click OK.
10. From the Standard group in the Toolbox, drag a Button control onto the page.
Note
The exact layout of the page is not important.

The Button control is on the page only so that you have a convenient way to post back the page to the server.
Now you will test the ads.
To test the ads
1. Press CTRL+F5 to run the page.
One of the two ads appears on the page.
2. Click Button several times to cause the page to post back.
The ad that appears randomly varies.
Note
Because there are only two ads, you might have to click Button several times before you see a different ad.

3. Click an ad.
You are redirected to the target page for that ad.
4. Close the browser.
Tracking Ad Responses
At this point, your page just displays ads that users can click to jump to another page. In this part of the walkthrough, you will
add functionality to keep track of how many times users click the ads. You will change the URL of the ads in the Sample.ads file
to send the ad response to a redirection page, with information in the query string that identifies the ad and the ultimate
destination.
You will then create a second XML file to store ad counter information. In a production Web site, you should not use an XML
file to track ad clicks, because the XML file would not support much traffic. However, for purposes of this walkthrough, you will
use an XML file for convenience, so that you do not have to configure database access. Additionally, in a production application,
you would probably want more sophisticated click tracking, such as making sure that you are tracking unique visitors, tracking
time and date information about clicks, and so on. Nevertheless, the overall strategy of using a redirection page to process
clicks is the same regardless of how you choose to track the data.
Finally, you will create the redirection page, where you will accumulate counters for different ads, and then redirect again to the
target page that the ad is intended to display.
To redirect ads to a tracking page
1. Open the Sample.ads file.
2. Set NavigateUrl to include the following:
The name of your redirection page (AdRedirector.aspx).
An identifier for each ad.
The page to which the ad ultimately points.
The following code listing shows the Sample.ads XML file updated with URLs that specify the AdRedirector.aspx page.
The ad identifier and target page are specified as a query string.
Note
Because the ampersand (&) is a reserved character in XML, the query string includes the entity reference &amp; instea
d.

<?xml version="1.0" encoding="utf-8" ?>


<Advertisements>
<Ad>
<ImageUrl>~/images/Contoso_ad.gif</ImageUrl>
<NavigateUrl>AdRedirector.aspx?ad=Widgets&amp;target=http://www.contoso.com/widget
s/</NavigateUrl>
<AlternateText>Ad for Contoso.com</AlternateText>
</Ad>
<Ad>
<ImageUrl>~/images/ASPNET_ad.gif</ImageUrl>
<NavigateUrl>AdRedirector.aspx?ad=ASPNET&amp;target=http://www.asp.net</NavigateUr
l>
<AlternateText>Ad for ASP.NET Web site</AlternateText>
</Ad>
</Advertisements>

3. Save the Sample.ads file, and then close it.


The next step is to create the XML file where you store counter information for the ad clicks. In a production Web site, you
would not need this step, because you would write information to a database instead. Using an XML file in this walkthrough
simplifies the steps that are required to track ad responses.
To create the XML file for tracking ad response
1. In Solution Explorer, right-click the App_Data folder, and then click Add New Item.
2. Under Templates, click XML File.
3. In the Name box, type AdResponses.xml, and then click Add.
A new XML file is created that contains only the XML directive.
4. Copy the following XML into the file, overwriting the XML directive.

<?xml version="1.0" standalone="yes"?>


<adResponses>
<ad adname="Widgets" hitCount="0" />
<ad adname="ASPNET" hitCount="0" />
</adResponses>

The file contains elements that have two pieces of information, the ID of an ad and a counter.
Note
If you assigned different IDs to the ads in the Sample.ads file in the previous procedure when you created the query stri
ngs, make sure that the IDs in the AdResponses.xml file match those.

5. Save the file, and then close it.


Note
Whether ASP.NET has Write permission for the XML file depends on which Web server you use. In this walkthrough, yo
u will use the ASP.NET Development Server, which is included with Visual Web Developer and has write access to the X
ML file. If you were using Microsoft Internet Information Services (IIS), the IIS Web server worker process may not have
write access to the XML file and you would have to explicitly set the Write permission. For more information on Web se
rvers in Visual Web Developer, see Web Servers in Visual Web Developer.
Now you will create the redirection page, which captures information about the ad that was clicked, updates the counter for the
ad, and then sends the request on to the page that is associated with the ad.
To create a Page_Load handler
1. In Solution Explorer, right-click the name of the Web site (for example, C:\WebSites), and then click Add New Item.
2. Under Visual Studio installed templates, click Web Form.
3. In the Name box, type AdRedirector.aspx, and then click Add.
This creates the page to which all ads will be directed when users click them. The page will not be displayed to users.
Therefore, you will not put any controls on it.
4. In Design view, double-click the page to create a Page_Load handler.
5. Copy the following code into the handler (do not overwrite the skeleton handler declaration).
VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles M
e.Load

Dim adName As String = Request.QueryString("ad")


Dim redirect As String = Request.QueryString("target")
If (adName Is Nothing Or redirect Is Nothing) Then
redirect = "TestAds.aspx"
End If

Dim doc As System.Xml.XmlDocument


Dim docPath As String = "~/App_Data/AdResponses.xml"

doc = New System.Xml.XmlDocument()


doc.Load(Server.MapPath(docPath))
Dim root As System.Xml.XmlNode = doc.DocumentElement
Dim xpathExpr As String
xpathExpr = "descendant::ad[@adname='" & adName & "']"
Dim adNode As System.Xml.XmlNode = _
root.SelectSingleNode(xpathExpr)
If adNode IsNot Nothing Then
Dim ctr As Integer = _
CInt(adNode.Attributes("hitCount").Value)
ctr += 1
Dim newAdNode As System.Xml.XmlNode = _
adNode.CloneNode(False)
newAdNode.Attributes("hitCount").Value = ctr.ToString()
root.ReplaceChild(newAdNode, adNode)
doc.Save(Server.MapPath(docPath))
End If
Response.Redirect(redirect)

End Sub

C#
protected void Page_Load(object sender, EventArgs e)
{
String adName = Request.QueryString["ad"];
String redirect = Request.QueryString["target"];
if (adName == null | redirect == null)
redirect = "TestAds.aspx";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
String docPath = @"~/App_Data/AdResponses.xml";
doc.Load(Server.MapPath(docPath));
System.Xml.XmlNode root = doc.DocumentElement;
System.Xml.XmlNode adNode =
root.SelectSingleNode(
@"descendant::ad[@adname='" + adName + "']");
if (adNode != null)
{
int ctr =
int.Parse(adNode.Attributes["hitCount"].Value);
ctr += 1;
System.Xml.XmlNode newAdNode = adNode.CloneNode(false);
newAdNode.Attributes["hitCount"].Value = ctr.ToString();
root.ReplaceChild(newAdNode, adNode);
doc.Save(Server.MapPath(docPath));
}
Response.Redirect(redirect);
}

The code reads the ad ID and URL from the query string. It then uses XML methods to read the AdResponse.xml file into
an XmlDocument object. The code locates the appropriate XML element using an XPath expression, extracts the
hitCounter value, and then updates the hitCounter value. Next, the code creates a copy of the XML element by cloning,
replaces the old element with the new one, and then writes the updated XML document back to disk. Finally, the code
redirects to the URL for the ad.
You will now test to confirm that the ad counters for the ads are working.
To test ad response tracking
1. Open the page that contains the AdRotator control, and then press CTRL+F5.
2. Click the ad.
You are redirected to the target page for that ad.
3. In the browser, click Back to return to the ad page.
4. Either click the ad again or click Button to display a different ad, and then click the ad.
5. Continue until you have clicked each ad at least one time, and one or more ads more than one time.
6. Close the browser.
7. In Visual Web Developer, open the AdResponse.xml file and verify that the counters for the ads reflect the number of
clicks from your test.
8. Close the AdResponse.xml file.
Displaying Ad Counter Data
For the final part of the walkthrough, you will create a page that displays the ad counter information, which is more convenient
than manually examining the XML file.
To create a page to display the ad response data
1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
2. Under Visual Studio installed templates, click Web Form.
3. In the Name box, type ViewAdData.aspx.
4. Click Add.
5. Switch to Design view.
6. From the Data group in the Toolbox,, drag an XmlDataSource control onto the page.
7. On the XmlDataSource Tasks shortcut menu, click Configure Data Source.
The Configure Data Source <Datasourcename> dialog box appears.
8. In the Data file box, type ~/App_Data/AdResponses.xml.
Alternatively, you can use Browse to locate the file.
9. Click OK.
10. From the Data group in the Toolbox, drag a GridView control onto the page.
11. On the GridView Tasks shortcut menu, in the Choose Data Source list, click XmlDataSource1.
12. Press CTRL+F5 to run the page.
The page displays the ad response data in a grid.
13. Close the browser.
Next Steps
There are more features available in the AdRotator control than have been illustrated in this walkthrough. You might want to
explore these features in the following ways:
Use additional attributes when you create ads in the XML file.
For example, you can use the Impressions element to control how often an advertisement is selected relative to the
other advertisements in the advertisement file. The higher the value, the more likely the ad will be selected. For detailed
information, see AdvertisementFile.
Use a database to track ad responses.
Note
In a production application, do not use an XML file to track ad responses, because it will not scale to support many user
s. This walkthrough uses an XML file for ad responses only to simplify the walkthrough and to make is to that you do n
ot have to configure a database.

Track additional information about ad clicks.


You might want to make sure that you are tracking unique visitors, perhaps by writing a cookie to the browser, if the user
has clicked the ad within the last day, or by tracking the IP address of the browser when you store click information. You
might also aggregate click information by date and time, and perhaps track ad information according to other dynamic
content on the source page, which can help you analyze traffic patterns.
Bind the AdRotator control to its data using a different data source control.
For example, you can store advertisement data in a database. If you do, you can add a data source control to the page
and configure it to use a query to obtain advertisement data. You can then bind the AdRotator control to the data source
control. For detailed information, see How to: Display Ads From a Database Using the AdRotator Web Server Control.
See Also
Reference
AdRotator Web Server Control Overview
Visual Web Developer

Walkthrough: Creating and Using an ASP.NET Web Service in


Visual Web Developer
In addition to letting you create Web pages, Microsoft Visual Studio also lets you create Web services that use ASP.NET XML.
Creating a Web service in Visual Studio is similar to creating a Web page. You can also use the Microsoft Visual Web Developer
Web development tool to reference and use Web services that are in a Visual Web Developer solution, on your local computer
or in a local or external UDDI directory. In this walkthrough, you will create the Web service in one solution and use it in
another.
Tasks illustrated in this walkthrough include:
Creating a simple XML Web service in Visual Web Developer.
Creating a separate Web site that uses the Web service.
Prerequisites
In order to complete this walkthrough, you will need:
Microsoft Internet Information Services (IIS) installed locally on your computer.
Creating a Web Service Under the IIS Root
Create a new Web service and page by following these steps.
Note
You must use an IIS Web site for this walkthrough.

To create a Web service


1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Service.
4. Click Browse.
5. Click Local IIS.
6. Click Default Web Site.
7. Click Create New Web Application.
Visual Web Developer creates a new IIS Web application.
8. Type the name TemperatureWebService.
9. Click Open.
The New Web Site dialog box appears, with the name of the new Web site in the rightmost Location list. The location
includes the protocol (http://) and location (localhost). This indicates that you are working with a local IIS Web site.
10. In the Language list, click the programming language that you prefer to work in.
The programming language that you choose will be the default for the Web site. However, you can use more than one
language in the same Web application by creating pages and components in different programming languages. For
more information about how to create components using different languages, see
Shared Code Folders in ASP.NET Web Sites.
11. Click OK.
Visual Web Developer creates the new Web service and opens a new class named Service, which is the default Web
service. However, in the following procedure you will create a new Web service with a specified name and you will not
use the Service class.
12. Close the Service class.
Creating the Web Service
You will create a Web service that converts temperature from Fahrenheit to Celsius and vice versa.
To create the Web service
1. In Solution Explorer, right-click the Web site name (http://localhost/TemperatureWebService), and then click Add New
Item.
2. Under Visual Studio installed templates, click Web Service, and then in the Name box, type Convert.
3. Make sure that the Place code in separate file check box is selected, and then click Add.
Visual Web Developer creates a new Web service that is made up of two files. The Convert.asmx file is the file that can be
invoked to call Web service methods, and it points to the code for the Web service. The code itself is in a class file
(Convert.vb, Convert.cs, or Convert.jsl, depending on the programming language) in the App_Code folder. The code file
contains a template for a Web service. The code file includes some code for a Web service method.
You will create two methods in the Web service. The first method converts Fahrenheit temperatures to Celsius, and the second
method converts Celsius temperatures to Fahrenheit.
To create the conversion methods
1. Add the following code inside the class, after the HelloWorld method:
VB
<System.Web.Services.WebMethod()> _
Public Function FahrenheitToCelsius(ByVal Fahrenheit As Double) _
As Double
Return ((Fahrenheit - 32) * 5) / 9
End Function

<System.Web.Services.WebMethod()> _
Public Function CelsiusToFahrenheit(ByVal Celsius As Double) _
As Double
Return ((Celsius * 9) / 5) + 32
End Function

C#
[System.Web.Services.WebMethod()]
public double FahrenheitToCelsius(double Fahrenheit)
{
return ((Fahrenheit - 32) * 5) / 9;
}

[System.Web.Services.WebMethod()]
public double CelsiusToFahrenheit(double Celsius)
{
return ((Celsius * 9) / 5) + 32;
}

Notice that the function names are preceded with an attribute ([System.Web.Services.WebMethod()] or
<System.Web.Services.WebMethod()>) as part of the function declaration.
2. After you have entered the functions, save the file.
Now, you can test the Web service in Visual Web Developer.
To test the Web service
1. In Solution Explorer, click Convert.asmx, and then press CTRL+F5.
The Web service is invoked and a page appears in the browser that shows the methods that are exposed by the Web
service.
2. Click CelsiusToFahrenheit, which invokes that method.
A page appears that prompts you for parameter values for the CelsiusToFahrenheit method.
3. In the Celsius box, type 100, and then click Invoke.
A new window appears that displays the XML that the Web service returns when the CelsiusToFahrenheit method is
invoked. The value 212 appears in the XML.
4. Close the browser that contains the method results.
5. In the original browser, click Back to return to the list of methods.
6. Click FahrenheitToCelsius and test to make sure that the method is returning the results that you expect.
If you type 212, the FahrenheitToCelsius method will return 100.
7. Close the browser.
You have finished creating the Web service; the next step is to use it.
Using the Web Service
Now that you have a Web service, you will create a Web site where you will reference and use the Web service that you
created. For the walkthrough, you will create a separate Web site that has a page where you start the Web service methods that
you just created.
To create a Web site to use the Web service
1. On the File menu, click New Web Site.
2. Under Visual Studio installed templates, click ASP.NET Web Site.
3. Click Browse.
4. Click Local IIS.
5. Click Default Web Site.
6. Click Create New Web Application.
Visual Web Developer creates a new IIS Web application.
7. Type the name TemperatureWeb.
8. Click Open.
9. In the Language list, click the programming language that you prefer to work in.
10. Click OK.
Visual Web Developer creates a new local IIS Web site and a new page named Default.aspx.
Adding the Web Service as a Component
The Web service is a component that you can reference in your application. Therefore, you must create a reference to it.
To create a reference to the Web service
1. In Solution Explorer, right-click the name of the Web site, and then click Add Web Reference.
The Add Web Reference dialog box appears, as shown in the following screen shot.
Add Web Reference dialog box

2. In the URL list, enter the following URL for the Web service, and then click Go:
http://localhost/TemperatureWebService/Convert.asmx
When Visual Web Developer finds the Web service, information about the Web service appears in the Add Web
References dialog box.
Note
If you cannot add a reference to a Web service, it might be that the proxy server is not configured correctly. In Microsof
t Internet Explorer, on the Tools menu, click Internet Options, click Connections, and then click LAN Settings. Select
the Bypass proxy server for local addresses check box. Additionally, set the proxy server address to the exact name
of the proxy server instead of allowing Internet Explorer to detect the proxy server. For more information, contact the n
etwork administrator.

3. Click one of the method links.


The test page for the method appears.
4. Click Add Reference.
Visual Web Developer creates an App_WebReferences folder and adds a folder to it for the new Web reference. By
default, Web references are assigned a namespace corresponding to their server name (in this case, localhost). Make a
note of the name for the Web reference namespace. In the folder, Visual Web Developer adds a .wsdl file that references
the Web service. It also adds supporting files, such as discovery (.disco and .discomap) files, that include information
about where the Web service is located.
Note
If the server name for the Web service contains characters that cannot be used for a class name, such as a hyphen (-), V
isual Web Developer converts those characters to an underscore character (_). Therefore, the namespace in Visual Web
Developer for the Web service might not match the server name exactly.

You can now use the Web service. In this walkthrough, you will add controls to Default.aspx, and then program the controls to
convert a specified temperature to both Fahrenheit and Celsius. When the page is running, it will look something like the
following illustration.
Temperature conversion page
To call the Web service methods
1. Open the Default.aspx page and switch to Design view.
2. From the Standard group in the Toolbox, drag the following controls onto the page and set their properties as indicated:
Control Properties
Textbox ID: TemperatureTextbox
Text: (empty)

Button ID: ConvertButton


Text: Convert

Label ID: FahrenheitLabel


Text: (empty)

Label ID: CelsiusLabel


Text: (empty)

3. Optionally, add text to the page for captions.


For this walkthrough, the layout of the page is not important.
4. Double-click ConvertButton to create an event handler for its Click event.
5. Make sure your event handler code matches the code in the following example.
VB
Dim wsConvert As New localhost.Convert()
Dim temperature As Double
temperature = System.Convert.ToDouble(TemperatureTextbox.Text)
FahrenheitLabel.Text = "Fahrenheit To Celsius = " & _
wsConvert.FahrenheitToCelsius(temperature).ToString()
CelsiusLabel.Text = "Celsius To Fahrenheit = " & _
wsConvert.CelsiusToFahrenheit(temperature).ToString()

C#
protected void ConvertButton_Click(object sender, EventArgs e)
{
localhost.Convert wsConvert = new localhost.Convert();
double temperature =
System.Convert.ToDouble(TemperatureTextbox.Text);
FahrenheitLabel.Text = "Fahrenheit To Celsius = " +
wsConvert.FahrenheitToCelsius(temperature).ToString();
CelsiusLabel.Text = "Celsius To Fahrenheit = " +
wsConvert.CelsiusToFahrenheit(temperature).ToString();
}

6. Press CTRL+F5 to run the page.


7. In the text box, type a value, such as 100, and then click Convert.
The page displays the result of converting the temperature value into both Fahrenheit and Celsius.
Debugging the Web Service
You can debug a Web service in the same way that you debug Web pages.
Note
Visual Web Developer Express edition and Visual Studio Standard edition do not support stepping into a Web service from a
page that references it. If you are using Visual Web Developer Express edition or Visual Studio Standard edition, skip this sect
ion and the ones following. For more information about how to debug Web sites, see
Walkthrough: Debugging Web Pages in Visual Web Developer.

To start, you must configure the Web site that contains the Web service to enable debugging.
To enable debugging in the Web services Web site
1. On the File menu, click Open Web Site.
2. Click Local IIS.
3. Click TemperatureWebService, and then click Open.
4. On the Website menu, click ASP.NET Configuration to open the Web Site Administration Tool.
Note
If this is the first time that you have run the Web Site Administration Tool, there might be some delay before it appears.

5. Click Application, and then click Application Configuration.


6. Under Debugging and Tracing, click Configure debugging and tracing.
7. Select the Enable debugging check box.
The Web Site Administration Tool creates a Web.config file for the Web site and sets a configuration option to enable
debugging.
Note
To see the Web.config file in Solution Explorer, click the Web site name and then, on the Solution Explorer toolbar, click
Refresh.

8. Close the Web Site Administration Tool.


You must now enable debugging for the Web site that uses the Web service.
To enable debugging in the Web site
1. Open the TemperatureWeb site.
2. On the Website menu, click ASP.NET Configuration to open the Web Site Administration Tool.
3. Click Application, click Application Configuration, under Debugging and Tracing, click Configure debugging
and tracing, and then select the Enable debugging check box.
4. Close the Web Site Administration Tool.
Note
To see the Web.config file in Solution Explorer, select the Web site name and then, on the Solution Explorer toolbar, clic
k Refresh.

5. In Solution Explorer, right-click Default.aspx, and then click View Code.


Visual Web Developer opens the code file for the page.
6. Position the pointer in the following line:
VB
temperature = System.Convert.ToDouble(TemperatureTextbox.Text)

C#
double temperature =
System.Convert.ToDouble(TemperatureTextbox.Text);

7. Press F9 to set a breakpoint on the line.


Testing Debugging
Both the Web site and the Web service are configured for debugging, so that you can now try debugging. You will start in the
Default.aspx page and step through the code until the code invokes the Web service. The debugger will switch to the Web
service and continue stepping through the code.
To debug the page and Web service
1. Press F5 to run the Default.aspx page with debugging.
The page appears in the browser.
2. In the box, type a value, such as 100, and then click Convert.
Visual Web Developer starts running the code for the page, but stops and highlights the line with the breakpoint on it.
3. Press F11 to step to the next line.
4. Press F11 again.
Because the next line invokes the Web service, the debugger steps into the Web service, stopping on the first line of the
FahrenheitToCelsius method.
5. Continue pressing F11.
The debugger steps through the rest of the method, and then returns to the calling page. If you continue stepping, the
debugger will step back into the Web service and into the CelsiusToFahrenheit method.
6. Close the browser, which also closes the debugger.
Next Steps
This walkthrough has illustrated the basic principles of creating a very simple Web service and using it in an ASP.NET
application. You might want to experiment with additional, more complex Web service features. Suggestions for additional
exploration include the following:
Understand the processing that occurs when you make an XML Web service call.
For more information, see Anatomy of an XML Web Service Lifetime.
Understand how to use XML Web services.
For more information, see XML Web Service Scenarios.
Create XML Web services that offer more sophisticated functionality than the simple Web service from this walkthrough.
You can create and chain asynchronous Web service method calls, use transactions, secure the Web services, configure
Web services for Microsoft Windows authentication, and so on.
For more information, see XML Web Services Using ASP.NET.
Learn about language-specific and technology-specific features provided by the XML Web services.
For more information, see XML Web Services in Visual FoxPro,
Introduction to Programming XML Web Services in Managed Code, Web Services (How Do I in Visual Basic),
XML Web Services Created with ATL Server, and Creating and Accessing XML Web Services Walkthroughs.
See Also
Tasks
Walkthrough: Debugging Web Pages in Visual Web Developer
Reference
@ WebService Directive in XML Web Services
<webServices> Element
Concepts
Design Guidelines for XML Web Services Created Using ASP.NET
Securing XML Web Services Created Using ASP.NET
Other Resources
Guided Tour of Creating Web Sites in Visual Web Developer
XML Web Services Using ASP.NET
Visual Web Developer

Walkthrough: Creating Web Pages for Mobile Devices


Mobile development in ASP.NET does not differ much from traditional ASP.NET browser-based Web development. ASP.NET
exposes a System.Web.Mobile namespace devoted specifically to Web development. You can create a Web page from the
MobilePage base class and add controls from the System.Web.Mobile namespace.
Mobile development follows the standard .NET Framework event-driven model in which your application responds to user
requests, button clicks, and so on.
In this walkthrough, you will create two Web pages that inherit from the MobilePage class and that are designed for a mobile
device. The first page will have a mortgage calculator that you can use to determine loan information. The second page
displays data in a format that is easy to page through on a small device. Tasks illustrated in this walkthrough include:
Creating an ASP.NET Web page that displays output on a device such as a mobile phone.
Adding paging so that users with small devices can move effectively through long lists.
Testing pages with a device emulator.
Prerequisites
To complete this walkthrough, you will need:
Ability to run the page on a device such as a mobile phone. Alternatively, you can use one of a number of emulators. In
this walkthrough, it is assumed that you have an emulator and that it is available on the same computer as your Web
server.
Note
You can run this walkthrough even if you have only a desktop browser. However, an emulator will more directly allow
you to see the functionality of the controls you will use in this walkthrough.

Access to Microsoft Internet Information Services (IIS) and permission to create a new application in IIS. It is
recommended that you use a local copy of IIS for the pages in the application, which makes it easiest to test the
application with your emulator. However, if you cannot create an application using IIS, you might still be able to use an
emulator with the Microsoft Visual Web Developer Web server. For details, see the "Next Steps" section at the end of this
walkthrough.
Creating the Web Site
If you have already created a Web site in Visual Web Developer (for example, by following the steps in
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and skip to the next section,
"Creating the Mortgage Calculator." Otherwise, create a new Web site and page by following these steps.
To create a new local IIS Web site under the IIS root
1. Open Visual Web Developer.
2. On the File menu, choose New, and then choose Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, select ASP.NET Web Site.
4. Click Browse.
The Choose Location dialog box appears.
5. Click the Local IIS tab.
6. Select Default Web Site.
7. Click the Create New Web Application button.
A new application is added under Default Web Site.
8. In the box for the new Web site, type DeviceWalkthrough and then click Open.
You are returned to the New Web Site dialog box with the Location box filled in with
http://localhost/DeviceWalkthrough.
9. In the Language list, select the programming language you prefer to work in.
The programming language you choose will be the default for your Web site. However, you can use multiple languages
in the same Web application by creating pages and components in different programming languages.
10. Click OK.
Visual Web Developer creates the new Web site and opens a new page named Default.aspx.
Creating the Mortgage Calculator
For the walkthrough, you will create a page that inherits from the MobilePage class and that contains a simple mortgage
calculator. The calculator prompts the user to enter a loan amount, a loan term in years, and the interest rate. The calculator can
determine the monthly payment for that loan.
In this walkthrough, you will use controls from the System.Web.Mobile namespace that are specifically designed for devices
that cannot display as much information as a desktop browser. Instead, the controls present information in separate views that
users can switch between.
To begin, you will delete the Default.aspx page and create a mobile page in its place.
To add a mobile page
1. Right-click the Default.aspx page in Solution Explorer and choose Delete.
2. Click OK in the dialog box.
3. Right-click the application in Solution Explorer and choose Add New Item.
4. Choose Mobile Web Form under Visual Studio installed templates.
5. Name the mobile Web page MobileCalculator.aspx and then click Add.
A Web page that inherits from the MobilePage class is created and added to your Web site.
Now that you have a mobile page, you will add controls that allow users to enter mortgage information.
To add controls for entering mortgage information
1. In the MobileCalculator.aspx page you created in the last procedure, make sure you are in Design view.
You will see a Form control with the default name of form1.
2. From the Mobile Web Forms folder of the Toolbox, drag controls onto form1 and set their properties as noted in the
following table.
Control Property settings
Label ID = HeadingLabel
Text = Loan Calculator

TextBox ID = PrincipalText
Text = Principal

TextBox ID = TermText
Text = Term in Years

TextBox ID = RateText
Text = Annual Rate
Command ID = Calculate
Text = Calculate

After you have created the Form where users enter their loan information, you will create another Form that will show the
results.
To create a form to display mortgage calculation results
1. From the Mobile Web Forms folder of the Toolbox, drag a Form control to the design surface.
The Form control is assigned the default ID of Form2.
2. From the Mobile Web Forms folder of the Toolbox, drag controls onto Form2 and set their properties as noted in the
following table.
Control Property settings
Label ID = LoanDetailsLabel
Text = Loan Details

Label ID = PaymentLabel
Text = Payment

Command ID = ReturnToCalculator
Text = Return to Calculator

You can now create the code that will calculate the loan information and display it.
To calculate the mortgage information and display results
1. If you are using C#, add a reference to the Microsoft.VisualBasic namespace so you can use the Pmt method to calculate
the payment information. Follow these steps:
a. In Solution Explorer, right-click the Web site name and choose Property Pages.
b. Click Add Reference.
c. In the .NET tab, select Microsoft.VisualBasic.dll and then click OK.
d. In the Property Pages dialog box, click OK.
2. In the form1 control, double-click the Calculate button to create a Click event handler, and then add the following code.
VB
Protected Sub Calculate_Click(ByVal sender As Object, _
ByVal e As EventArgs)

' Get values from the form


Dim principal As Double = Convert.ToDouble(PrincipalText.Text)
Dim apr As Double = Convert.ToDouble(RateText.Text)
Dim monthlyInterest As Double = apr / (12 * 100)
Dim termInMonths As Double = Convert.ToDouble(TermText.Text) * 12
Dim monthlyPayment As Double

' Calculate the monthly payment


monthlyPayment = Microsoft.VisualBasic.Financial.Pmt( _
monthlyInterest, termInMonths, -principal, 0, _
DueDate.BegOfPeriod)

' Change to the other form


Me.ActiveForm = Me.form2

' Display the resulting details


Dim detailsSpec As String = "{0} @ {1}% for {2} years"
LoanDetailsLabel.Text = String.Format(detailsSpec, _
principal.ToString("C0"), apr.ToString(), TermText.Text)
PaymentLabel.Text = "Payment: " & monthlyPayment.ToString("C")
End Sub

C#
protected void Calculate_Click(object sender, EventArgs e)
{
// Get values from the form
Double principal = Convert.ToDouble(PrincipalText.Text);
Double apr = Convert.ToDouble(RateText.Text);
Double monthlyInterest = (Double)(apr / (12 * 100));
Double termInMonths = Convert.ToDouble(TermText.Text) * 12;
Double monthlyPayment;

// Calculate the monthly payment


monthlyPayment = Microsoft.VisualBasic.Financial.Pmt(
monthlyInterest, termInMonths, -principal, 0,
Microsoft.VisualBasic.DueDate.BegOfPeriod);

// Change to the other form


this.ActiveForm = this.form2;

// Display the resulting details


string detailsSpec = "{0} @ {1}% for {2} years";
LoanDetailsLabel.Text = String.Format(detailsSpec,
principal.ToString("C0"), apr.ToString(), TermText.Text);
PaymentLabel.Text = "Payment: " + monthlyPayment.ToString("C");
}

The code gathers the values from the text boxes, converts them to appropriate data types, and then uses them as
parameters for the Visual Basic Pmt function to calculate the monthly cost of the mortgage. (You can use the Visual Basic
function in any language as long as you fully qualify the function call with the namespace.) After calculating the monthly
amount, the code switches to the second Form control and displays the results in the respective Label controls.
3. In the Form2 control, double-click the Command control to create a Click event handler, and then add the following
highlighted code.
VB
Protected Sub ReturnToCalculator_Click(ByVal sender As Object, _
ByVal e As EventArgs)

Me.ActiveForm = Me.form1
End Sub

C#
protected void ReturnToCalculator_Click(object sender, EventArgs e)
{
this.ActiveForm = this.form1;
}
Testing the Calculator
You are now ready to test the calculator. You can test the calculator in a desktop browser. However, a more interesting test is to
use your device emulator.
To test the calculator
1. Press CTRL+F5 to see your page in the default browser, and to get the exact URL.
The first form appears on the page.
2. Start your emulator and connect to the URL for your page.
3. When the page appears in the emulator, enter a loan amount of 100000, the number of years as 30, and a percentage
rate of 5, and then click Calculate.
The calculator is replaced by the results view, with the result 534.59.
Adding Pagination
Many devices have small display areas, making it impractical to display long lists. ASP.NET provides an ObjectList control
designed for mobile devices that can automatically display an entire screen of information at one time and provide links so
that users can move forward and backward in the list.
In this section of the walkthrough, you will create a data listing that displays more information than can be shown on one
screen of even a desktop browser. By adding an ObjectList control, you will automatically add paging capability to the output,
appropriately sized to the browser the user has.
The first thing you need to do is create a mobile Web Forms page and add an ObjectList control to it.
To add a mobile Web Forms page and create an ObjectList control on it
1. Right-click the application in Solution Explorer and choose Add New Item.
2. Choose Mobile Web Form under Visual Studio installed templates.
3. Name the page MobilePaging.aspx and then click Add.
A Web page that inherits from the MobilePage class is created and added to your project. The page includes a Form
control named form1 on it. You can only use controls in the System.Web.Mobile namespace on a page that inherits
from the MobilePage class.
4. From the Mobile Web Forms folder of the Toolbox, drag an ObjectList control to the design surface and place it on
form1.
An ObjectList control is added to your page. It shows a generic set of data that gives you an idea of what the control will
look like when it is rendered on the client.
After the ObjectList control is created, you need to create data that will populate the control.
To create the data
1. In the MobilePaging.aspx page, switch to Design view and double-click the empty design surface to create an empty
event handler for the page Load event.
2. In the empty handler, add the following code.
VB
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As EventArgs)

' Create and fill an array of strings


Dim listItems(25) As String

Dim i As Integer
For i = 0 To 24
listItems(i) = _
String.Format("This is item {0}.", i)
Next

' Bind the ObjectList to the Items


Me.ObjectList1.DataSource = listItems
Me.ObjectList1.DataBind()
End Sub

C#
protected void Page_Load(object sender, EventArgs e)
{
// Create and fill an array of strings
string[] listItems = new string[25];
for (int i = 0; i < 25; i++)
listItems[i] =
String.Format("This is item {0}.", i);

// Bind the ObjectList to the Items


this.ObjectList1.DataSource = listItems;
this.ObjectList1.DataBind();
}

The code creates an array of string objects and populates it with strings. It then binds that array to the ObjectList control.
You can now test the page.
To test the page
1. Press CTRL+F5 to run the page.
The page is displayed with a long list of numbered items.
2. Start your device emulator and type in the URL of the page (http://localhost/DeviceWalkthrough/paging.aspx).
Notice that the data is displayed in a long list.
Adding Paging
Now that you have a page that displays data, you can add paging so that the display is automatically sized to the size of the
screen in the device.
To add paging
1. In the MobilePaging.aspx page, switch to Design view and then select form1.
2. In the Properties window, set the Paginate property to true.
3. Select the ObjectList control and, in the Properties window, set the ItemsPerPage property to 5.
You can now test paging.
To test paging
1. Press CTRL+F5 to run the page in Internet Explorer.
The page is displayed with a page of data and a navigation control.
2. Use the Next and Previous links to move through the data.
3. In your device emulator, enter the URL of the page.
The emulator displays a page of data (five items). If necessary, you can scroll the page up or down.
4. Use the links to move to other pages showing more items.
Next Steps
In this walkthrough, you have created a page that is tailored to devices by taking advantage of controls that are designed for
devices with limited display areas. ASP.NET and Visual Web Developer include facilities for creating applications for a wide
range of devices and browsers.
You also might want to explore the following aspects of devices:
Depending on what emulator you use, you might be able to integrate the emulator into Visual Web Developer. In
Solution Explorer, right-click the mortgage calculator page and choose Browse With. Click Add and type the information
for your emulator to add it to the list of browsers. You can then use the Browse With command to view a page in the
emulator. Note that not all emulators are supported.
See Also
Concepts
ASP.NET Mobile Web Development Overview
Architectural Overview of Adaptive Control Behavior
ASP.NET Device Filtering Overview
Visual Web Developer

Walkthrough: Using Resources for Localization with ASP.NET


An effective way to create localized Web pages is to use resources for your page's text and controls based on the user's
language and culture. By using properties placed in resource objects, ASP.NET can select the correct property at run time
according to the user's language and culture. The process is straightforward:
A resource file (.resx) stores values.
In your page, you indicate that controls should use resources for their property values.
At run time, the controls' property values are derived from the resource file.
Note
In practice, you can store values in custom resources objects, such as a database. However, in this walkthrough you will
use a .resx file to store values.

Visual Web Developer allows you to generate resources for controls, control properties, and HTML for your controls without
writing any code.
Tasks illustrated in this walkthrough include:
Enabling localization of ASP.NET pages.
Generating a resource file and implicitly associating its values with the controls in your application.
Creating localization resource files and explicitly referencing them in your pages by using declarative expressions.
Prerequisites
In order to complete this walkthrough, you will need:
Visual Web Developer (Visual Studio).
The .NET Framework.
Creating a Web Site
If you have already created a Web site in Visual Web Developer (see
Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site and go to the next section,
"Implicit Localization with ASP.NET." Otherwise, create a new Web site and page by using the steps in the following procedure.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the Location box, enter the name of the folder where you want to keep the pages of your Web site.
For example, type the folder name C:\WebSites.
5. In the Language list, click the programming language you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Implicit Localization with ASP.NET
In this section, you will work with implicit localization. In implicit localization, you specify that control properties should
automatically be read from a resource file, but you do not need to explicitly specify which properties are localized. Then, you
create a resource file with localized values for specific properties. At run time, ASP.NET examines the controls on the page. If
the control is marked to use implicit localization, ASP.NET looks through the resource file for the page. If it finds property
settings for the marked control, ASP.NET substitutes the values in the resource file for those in the control.
In this example of implicit localization, you use a combination of the designer and the Resource Editor to generate a default
resource file that you will use as a starting point for localization in two languages. Visual Web Developer will generate a
resource file based only on the controls on your page. For this reason, it is a good idea to generate the resource file after you
have completed your page's control layout, including simple controls such as buttons, labels, and text boxes.
To place controls on a page
1. In Solution Explorer, right-click Default.aspx, click Rename, and then type Sample.aspx.
Doing this will help avoid confusion in the rest of the walkthrough with regard to default resource files because implicit
resource file names use page names.
2. Open Sample.aspx, and then switch to Design view.
3. In the Toolbox, from the Standard section, drag a Button, a Label, and a TextBox control onto the page.
4. For each control, set Text to English Button, English Label, and English TextBox, respectively.
After creating the page and adding the controls, you can use a Visual Web Developer command to generate a local resource
file for this page. The local resource file will contain the resource strings for the controls on the page. Visual Web Developer
generates a resource string for each property that is designated internally in the control as localizable. Each control can have
different properties designated as localizable, although most text-based properties are marked that way.
To automatically generate a resource file
1. Click the designer surface or a control.
2. On the Tools menu, click Generate Local Resource.
Visual Web Developer creates a new folder named App_LocalResources, and within the App_LocalResources folder, a
new file named Sample.aspx.resx. If you named your page something other than Sample.aspx, the .resx file will reflect
whatever name you chose. When using implicit localization, resource file names are based on individual page names.
3. Switch to Source view to see the changes to your control declarations.
Visual Web Developer has added an attribute to your controls to retrieve their values from your newly created resource
file. For example, the Button control's markup has a new meta:resourcekey attribute.

<asp:Button ID="Button1" Runat="server" meta:resourcekey="ButtonResource1" Text="Engli


sh Button" />

When a browser sends a request to Web server, the request can include information about the current language and culture.
For example, a browser might send the string "en-us" to indicate it has been set to use United States English; another browser
might send the string "en-gb" to indicate it has been set to use British English.
Note
The language and culture settings in a browser request are not a completely reliable way to detect the user's preferred langu
age. The settings indicate only what the browser has been set to send or has inherited from the underlying operating system.
For this walkthrough, you will rely on the language and culture settings, but in a production application you should also inclu
de a way for users to select a language and culture manually.

The resource file is used as the default resource file for all requests. (It is the resource file for the fallback culture.) If no culture
is specified by the browser, or if the browser request includes a language or culture that you do not support, resource values
are pulled from this default file.
Now that the resource file is created, you can place localized text within it by using the Resource Editor.
To edit the resource file by using the Resource Editor
1. In Solution Explorer, open Sample.aspx.resx.
In the Resource Editor, under Value, are the Text properties for each of the controls that you placed onto your page.
Changing the value here will change the value for the default culture.
2. Set ButtonResource1.Text to Edited English Text.
3. Save the file.
Now you can test the page.
To test the page
Press CTRL+F5 to run the page.
The text you provided in the Resource Editor is shown as the label for Button1. When using implicit localization, syntax
properties in resource files will override properties specified in the page itself.
Adding Other Cultures
Each language and culture combination requires a unique resource file. To add other cultures, you can use your default file as a
starting point. You can create resource files for different cultures and locales by creating new resource files in which the ISO
language codes are part of the file name (for example, en-us, fr-ca, and en-gb). These ISO codes are placed between the page
name and the .resx file name extension, as in Sample.aspx.en-us.resx. To specify a culturally neutral language, you would
eliminate the country code, such as Sample.aspx.fr.resx for the French language.
Note
When using implicit localization syntax, you must create a separate series of resource files for each page.

To create a culturally neutral French language file


1. In Solution Explorer, right-click the Sample.aspx.resx file, and then click Copy.
2. Right-click the App_LocalResources folder, and then click Paste.
Visual Web Developer creates a file named Copy of Sample.aspx.resx.
3. Right-click the Copy of Sample.aspx.resx file, click Rename, and then type Sample.aspx.fr.resx.
Sample.aspx.fr.resx indicates a file for culturally neutral French language text.
4. Open Sample.aspx.fr.resx.
5. For the Button, Label, and TextBox controls, set Text to French Button, French Label, and French TextBox,
respectively.
6. Save the file.
Testing with an Alternate Language Setting
Before you can see if this new resource file is used by ASP.NET, you must alter your browser settings to request the desired
culture.
To change your browser's language settings
1. In Microsoft Internet Explorer, on the Tools menu, click Internet Options.
2. Click Languages.
3. In the Language Preference dialog box, click Add.
4. In the Add Language dialog box, under Languages, click French (France) [fr], and then click OK.
5. Click Add and add Spanish (Mexico) [es-mx] to the list of languages.
6. Click Add and add Arabic (Egypt) [ar-eg] to the list of languages.
You will use Spanish and Arabic for testing later in this walkthrough.
7. In the Language Preference dialog box, under Language, click French (France) [fr], click Move Up, and then click OK.
Internet Explorer is now set to pass fr as the language setting for any request. With the culture set to auto in the Sample.aspx
page, ASP.NET will attempt to locate a resource file and its corresponding values to assemble the page according to your
language and culture preferences.
To test the page
In Visual Web Developer, press CTRL+F5 to run the page.
The page is refreshed with values from the localized French language file instead of the English version.
Note
You can reset your language settings in Internet Explorer by returning to the Language Preference dialog box and m
oving your chosen language back up in the list.

Explicit Localization with ASP.NET


In the first part of this walkthrough, you used ASP.NET implicit localization to have controls display localized text. You
generated a resource file with property values in it, and in the process, you added an attribute to each control that instructed it
to fill its property values, if any, from the resource file. Implicit localization works automatically, in that you do not need to
specify property by property how to read information from a resource file.
However, at times you want to have more direct control over how properties are set. For this, instead of using implicit
localization, you can use explicit localization. With explicit localization, you set the value of a property by using an expression
pointing to a resource file. When the page runs, the expression is evaluated, the value is read from the specified resource file,
and then the value is used to set the property.
Explicit localization is useful when you have large bodies of text or custom messages you want to localize, in addition to
controls and labels. For example, you could develop a series of localized welcome and thank you messages for an e-commerce
site, and use explicit declarative expressions to place this text on your pages. Additionally, explicit localization allows you to
maintain a single set of localized resource files rather than maintaining a separate set of files for each page.
In this section, you will create resource files manually and reference them by using ASP.NET declarative expression syntax. You
will create a resource file for a simple thank you message. Unlike using the designer, a separate resource file is not required for
each ASP.NET page.
The base name of your resource file will be LocalizedText. For each language you want to localize, you will create another file
with the appropriate language code (and optionally the culture code) as part of the file name. For example, for U.S. English you
would create a file named LocalizedText.resx. For the French language in Canada, you would create a file named
LocalizedText.fr-ca.resx. Both files would be placed under the Resources directory of your Web application. Unlike the implicit
example previously, you do not need to maintain a resource file for each .aspx page; instead, you can maintain a single series of
files for each language or culture you support.
To create a resource file
1. In Solution Explorer, right-click the root of your Web site, click Add ASP.NET Folder, and then click
App_GlobalResources.
2. Right-click the App_GlobalResources folder, and then click Add New Item.
3. Under Visual Studio installed templates, click Resource File.
4. In the Name box, type LocalizedText.resx, and then click Add.
The LocalizedText.resx file will act as the resource for the fallback culture.
5. Create a second .resx file and name it LocalizedText.fr.resx.
The string "fr" identifies the file as the resource to use if the browser's language is set to French (regardless of culture).
6. Create a third .resx file and name it LocalizedText.es-mx.resx.
The string "es-mx" identifies the file as file as the resource to use if the browser's language is set to Spanish (Mexico).
7. Open the LocalizedText.resx file.
8. In the first row under the Name column type Msg1.
9. In the first row under the Value column, type Hello.
10. Save the file and close it.
11. Open the LocalizedText.fr.resx, create a resource string named Msg1, assign it the value Bon jour. When you are
finished, save and close the file.
12. Open the LocalizedText.es-mx.resx, create a resource string named Msg1, assign it the value Buenos días. When you
are finished, save and close the file.
Note
To insert the letter with acute (í), type ALT+0237 on the numeric keypad with Number Lock on.

You have created three values for the resource named Msg1. ASP.NET will read the value out of the appropriate resource
file based on what language the browser is set to.
Now that your resource file is created, you can return to the page and add controls that will reference the resource.
To add a Label control to the page
1. Switch to Sample.aspx, and then switch to Design view.
2. Drag another Label control onto the page.
3. Right-click the Label control, click Properties, and then click the ellipsis (…) button in the Expressions box.
The Expressions dialog box appears.
4. In the Bindable Properties list, click Text.
5. In the Expression Type list, select Resources.
6. Under Expression Properties, set ClassKey to LocalizedText and ResourceKey to Msg1.
7. Click OK.
8. Switch to Source view.
Your label's text attribute now has an explicit expression stating the base file from which to retrieve the resource and the
key to select.

<asp:Label ID="Label2" Runat="server" Text="<%$ Resources:LocalizedText, Msg1 %>">

Note
The LocalizedText attribute has no language indicator, culture indicator, or .resx extension because it is not the actual f
ile name. Instead, LocalizedText represents the base resource class. Depending on the culture sent by the browser, AS
P.NET will select the resource out of the file with the appropriate language or culture code within its file name, such as
LocalizedText.fr.resx, LocalizedText.es-mx.resx, or if no matching language is found, LocalizedText.resx.

With the resource file completed, and the declarative expression added, you can test the page. After the last test, your browser
was set to report French as its language preference. During the testing, you will change the browser's language several times.
To test the page
1. Press CTRL+F5 to run the page.
The French-language version of the text you provided in the Resource Editor is shown as the text for the Label control.
2. In Microsoft Internet Explorer, on the Tools menu, click Internet Options.
3. Click Languages.
4. In the Language Preference dialog box, move Spanish (Mexico) [es-mx] to the top of the list of languages. When you
are finished, click OK and close the Internet Options dialog box.
5. Press F5 to refresh the browser.
The Spanish version of the text is displayed.
6. Change the language to Arabic and then press F5 to refresh the page again.
This time, the text is displayed in the language you used in the fallback resource file. Because you did not create a file
LocalizedText.ar-eg.resx, ASP.NET was not able to locate text that matched the language and culture reported by the
browser, so it used the fallback resource file.
7. When you are finished testing the page, set the language back to the language your preferred language.
Next Steps
Localization can be a complex undertaking. This walkthrough has illustrated some of the features in Visual Web Developer that
can eliminate some of the work. You might want to learn more about localization and ASP.NET. For example, you might want
to:
Learn more about using resources in your applications. For details, see Resources in Applications.
Use classes that define culture-related information, including the language, country or region, calendars in use, format
patterns for dates, currency, numbers, and sort order for strings. For details, see System.Globalization.
Learn more about best practices to use when coding for a global audience. For details, see
Best Practices for Developing World-Ready Applications.
See Also
Concepts
Using the CultureInfo Class
Other Resources
Encoding and Localization
Globalization and Localization Namespaces in Visual Studio
Visual Web Developer

Building Professional Web Sites


The topics in this section include step-by-step walkthroughs that illustrate how to use system diagnostics with ASP.NET Web
pages and show how to deploy a Web site to a production Web server.
In This Section
Walkthrough: Integrating ASP.NET Tracing with System.Diagnostics Tracing
Walkthrough: Copying a Web Site Using the Copy Web Site Tool
Walkthrough: Publishing a Web Site
Related Sections
Guided Tour of Creating Web Sites in Visual Web Developer
Contains topics that give a guided tour of creating Web sites in Visual Web Developer.
ASP.NET

Walkthrough: Integrating ASP.NET Tracing with


System.Diagnostics Tracing
This walkthrough describes how to integrate ASP.NET tracing techniques with System.Diagnostics tracing techniques and write
all trace messages to a single tracing output.
You can use tracing to track the flow of execution for your application, to display data at critical points during a Web form's life
cycle, and to discover how the Web forms interact with various other components of your application. Using tracing, you can
examine HTTP request parameters that are submitted to your application, how much memory is being stored in view state for
a particular Web form, and other useful profiling information.
The ASP.NET tracing mechanism writes messages that are displayed on ASP.NET Web pages and on the ASP.NET Trace viewer
(Trace.axd), whereas the Trace class is used to write trace messages to the standard .NET Framework trace output (typically a
console window). To make it easier to track how the Web forms interact with business objects and other components, you can
integrate ASP.NET tracing output with System.Diagnostics tracing to route all tracing messages to one of these outputs.
Common scenarios that use both ASP.NET tracing and the Trace class include Web pages that use middle-tier business objects
to interact with data and business rules and pages that use enterprise services, such as transactions and queues. In these
situations, the business and enterprise components play key parts in the successful execution of the page and monitoring the
execution flow of the pages across the multiple tiers of your application using a single tracing output is desirable.
In this walkthrough you will work with tracing. You will modify a Web page and a business object to write trace messages, and
then route all messages to one tracing output.
Tasks illustrated in this walkthrough include the following:
Creating a custom business component that can return data to a Web page. The component reads data from an XML file.
Creating a Web page that references the custom business object as a data source.
Enabling tracing for the Web page that is referencing the business object.
Writing trace messages to the Web page that is referencing the business object.
Writing Trace messages in a custom business object.
Configuring an ASP.NET application to write all trace messages to a single output.
Reading trace output.
Prerequisites
In order to complete this walkthrough, you need the following:
The Microsoft .NET Framework and an existing ASP.NET Web site.
Note
This walkthrough does not assume that you are using a designer, such as the Microsoft Visual Web Developer Web develop
ment tool or Microsoft Visual Studio.

Creating a Web Page and Business Object


In this walkthrough you will create the Default.aspx Web page, an AuthorClass business object, and the Authors.xml XML data
file that is required for later steps in this walkthrough that involve tracing.
You can copy and paste the source code into files in your ASP.NET directory. This will create the Default.aspx Web page,
AuthorClass business object, and Authors.xml file.
To create the Default.aspx page
1. Open a text editor, such as Notepad, and create a new file.
2. Enter the following code into the file.
VB
<%@ Page Language="VB" %>
<html>
<form runat="server">
<asp:objectdatasource
id="AuthorsObjectDataSource"
runat="server"
typename="PubsClasses.AuthorClass"
selectmethod="GetAuthors"/>

<asp:gridview
id="GridView1"
runat="server"
datasourceid="AuthorsObjectDataSource" />
</form>
</html>

C#
<%@ Page Language="C#" %>
<html>
<form runat="server">
<asp:objectdatasource
id="AuthorsObjectDataSource"
runat="server"
typename="PubsClasses.AuthorClass"
selectmethod="GetAuthors"/>

<asp:gridview
id="GridView1"
runat="server"
datasourceid="AuthorsObjectDataSource" />
</form>
</html>

3. Save the file in the ASP.NET application root directory as Default.aspx.


The Default.aspx page uses a business object named AuthorClass to interact with XML data.
To create the AuthorClass business object
1. Under the application root directory, create a directory named App_Code.
2. In a text editor, such as Notepad, open a new file.
3. Enter the following code into the file.
VB
Imports Microsoft.VisualBasic
Imports System
Imports System.Web
Imports System.Data
Namespace PubsClasses
Public Class AuthorClass
Private dsAuthors As DataSet = _
New System.Data.DataSet("ds1")
Private filePath As String = _
HttpContext.Current.Server.MapPath("~/App_Data/authors.xml")
Public Sub New()
dsAuthors.ReadXml(filePath, Data.XmlReadMode.ReadSchema)
End Sub
Public Function GetAuthors() As DataSet
Return dsAuthors
End Function
End Class
End Namespace

C#
using System;
using System.Web;
using System.Data;
namespace PubsClasses
{
public class AuthorClass
{
private DataSet dsAuthors = new DataSet("ds1");
private String filePath =
HttpContext.Current.Server.MapPath("~/App_Data/authors.xml");

public AuthorClass()
{
dsAuthors.ReadXml (filePath, XmlReadMode.ReadSchema);
}

public DataSet GetAuthors ()


{
return dsAuthors;
}
}
}

4. In the App_Code directory, save the file as AuthorClass.cs (for C#) or AuthorClass.vb (for Microsoft Visual Basic).
The data file that the AuthorClass uses is Authors.xml.
To enable tracing and display ASP.NET trace messages
1. Under the application root directory, create a directory named App_Data.
2. In a text editor, such as Notepad, open a new file.
3. Enter the following XML data into the file.
The XML file includes schema information that identifies the database structure of the data. This includes a primary-key
constraint for the key.
Note
Business components can work with data in any way that is suited for your application. This walkthrough uses an XML f
ile for convenience.

<?xml version="1.0" standalone="yes"?>


<dsPubs xmlns="http://www.tempuri.org/dsPubs.xsd">
<xs:schema id="dsPubs" targetNamespace="http://www.tempuri.org/dsPubs.xsd" xmlns:mstns
="http://www.tempuri.org/dsPubs.xsd" xmlns="http://www.tempuri.org/dsPubs.xsd" xmlns:x
s="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdat
a" attributeFormDefault="qualified" elementFormDefault="qualified">
<xs:element name="dsPubs" msdata:IsDataSet="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="authors">
<xs:complexType>
<xs:sequence>
<xs:element name="au_id" type="xs:string" />
<xs:element name="au_lname" type="xs:string" />
<xs:element name="au_fname" type="xs:string" />
<xs:element name="au_phone" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
<xs:unique name="Constraint1" msdata:PrimaryKey="true">
<xs:selector xpath=".//mstns:authors" />
<xs:field xpath="mstns:au_id" />
</xs:unique>
</xs:element>
</xs:schema>
<authors>
<au_id>172-32-1176</au_id>
<au_lname>White</au_lname>
<au_fname>Gerry</au_fname>
<au_phone>408 496-7223</au_phone>
</authors>
<authors>
<au_id>213-46-8915</au_id>
<au_lname>Green</au_lname>
<au_fname>Marjorie</au_fname>
<au_phone>415 986-7020</au_phone>
</authors>
</dsPubs>

4. In the App_Data directory, save the file as Authors.xml, and then close it.
Adding Trace Messages to a Web page and Business Object
When you have created the Default.aspx page, the Authors.xml data file, and the AuthorClass business object, you can start
working with tracing. Before you add any trace messages to your code, enable tracing for the Default.aspx page.
To enable tracing and display ASP.NET trace messages
1. In a text editor, such as Notepad, open the Default.aspx page.
2. Add a Trace attribute to the @ Page directive, and then set Trace to true.
The declaration enables ASP.NET tracing for the Web page.
For more information, see How to: Enable Tracing for an ASP.NET Page.
Page tracing is now enabled and when you view the page in a Web browser, you will see that the GridView control is followed
by tracing output. The second tracing table that is displayed, Trace Information, shows you detailed information about the
execution path for the Web page.
For more information about how to read the tracing output, see the Reading ASP.NET Trace Information topic.
Writing Trace Messages
To better understand where some basic ASP.NET actions occur, such as the data binding that is performed by the GridView
control in the Default.aspx page, add trace messages to the Web page and AuthorClass business object.
To write trace messages from a Web form
In your Default.aspx Web page, enter the following code after the @ Page directive but before the <html> tag.
VB
<script runat="server">

Private Sub Page_Load(sender As Object, e As EventArgs)


Trace.WriteLine("ASP.NET TRACE","page_load called.")
Trace.WriteLine("ASP.NET TRACE","page_load finished.")
End Sub ' Page_Load

</script>

C#
<script runat="server">
private void page_load(object sender, EventArgs e) {

Trace.WriteLine("ASP.NET TRACE","page_load called.");


Trace.WriteLine("ASP.NET TRACE","page_load finished.");
}
</script>

Note
You might have to include a language attribute in your @ Page directive, depending on which language you use.

These trace messages are written to the ASP.NET trace output, and when you view the Default.aspx page again, you will see the
trace messages in the Trace Information section, between "Begin Load" and "End Load". "Begin Load" and "End Load"
are associated with the Page_Load method.
Now, you will add trace messages to the business object, AuthorClass.
To write trace messages to the AuthorClass business object
1. Enter the following code into the AuthorClass constructor.
VB
System.Diagnostics.Trace.Write("AuthorClass is created.", "AUTHORCLASS TRACE")

C#
System.Diagnostics.Trace.Write("AuthorClass is created.", "AUTHORCLASS TRACE");

2. Enter the following code into the AuthorClass.GetAuthors method.


VB
System.Diagnostics.Trace.Write("GetAuthors called.","AUTHORCLASS TRACE")

C#
System.Diagnostics.Trace.Write("GetAuthors called.","AUTHORCLASS TRACE");

Note
When you use ASP.NET System.Web.TraceContext.Write method, the trace category comes in front of the trace messag
e in the parameter list for the method. However, when you use the .NET Framework tracing Write method, the trace me
ssage comes in front of the trace category.

If you compile the business object that has the TRACE compiler option, these trace messages are written to the system trace
output. The trace messages are not written to the Default.aspx page, as the ASP.NET trace messages are. To test this, view the
Default.aspx page and verify that only the same "ASP.NET TRACE" messages appear in the Trace Information table that you
saw before.
In the next section, you will learn how to configure your ASP.NET Web application to automatically compile with the TRACE
option enabled and to route all trace messages to the Web page.
Routing All Tracing Output to the Web Form
Routing the Trace messages that are contained in the AuthorClass business object to the ASP.NET trace output can show you
when the AuthorClass is created and manipulated during request processing and give you a more holistic view of what your
application is doing. To route Trace messages to an ASP.NET Web page, you must add a WebPageTraceListener object. You
can add a trace listener either through configuration (recommended) or programmatically. For more information about adding
a trace listener through configuration, see <listeners> Element for <trace>.
For the next procedure, you will need a Web.config file. If you already have a Web.config file, skip the next procedure and go to
the following one, in which you will add a WebPageTraceListener object.
To create a Web.config file
1. Open a text editor, such as Notepad, and create a new file.
2. Enter the following text into the file.

<!-- Web.Config Configuration File -->


<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>

3. Save the file in the same directory as Default.aspx as Web.config.


Next, you will add a WebPageTraceListener object to your application to route Trace messages to the ASP.NET tracing
output.
To add a WebPageTraceListener for your application through configuration
1. Open the Web.config file for your application.
2. Place the following code in your Web.config file after the <system.web> section.

<system.diagnostics>
<trace>
<listeners>
<add name="WebPageTraceListener"
type="System.Web.WebPageTraceListener, System.Web, Version=2.0.3600.0, Cul
ture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</listeners>
</trace>
</system.diagnostics>

This configuration section adds a WebPageTraceListener object to the trace listeners collection for your application.
Adding a WebPageTraceListener using the configuration file for your application is the recommended method of adding a
trace listener. However, you can also add the trace listener programmatically, which is especially useful, if you are using
complex tracing logic and different types of trace listeners to trace your application, and the WebPageTraceListener is just
one of many.
If you want to add a trace listener to your application programmatically, create a Global.asax file and add the listener by
following these steps.
To create a Global.asax file and add a trace listener programmatically
1. Open a text editor, such as Notepad, and create a new file.
2. Enter following code into the file.
VB
<%@ Application Language="VB" %>
<%@ Import Namespace="System.Web" %>

<script runat="server">
Sub Application_Start(sender As Object, e As EventArgs)
' Code that runs when the application is started.
End Sub

Sub Application_End(sender As Object, e As EventArgs)


' Code that runs when the application shuts down.
End Sub
</script>

C#
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web" %>

<script runat="server">

void Application_Start(Object sender, EventArgs e) {


// Code that runs when the application is started.
}

void Application_End(Object sender, EventArgs e) {


// Code that runs when the application shuts down.
}
</script>

3. In your application root directory, save the file as Global.asax.


This creates a basic Global.asax, which is a compiled module that contains code that runs whenever the application is
started or stopped.
4. Enter the following code into the Application_Start method of your Global.asax file.
VB
' Create a trace listener for Web forms.
Dim gbTraceListener As New WebPageTraceListener()
' Add the event log trace listener to the collection.
System.Diagnostics.Trace.Listeners.Add(gbTraceListener)

C#
// Create a trace listener for Web forms.
WebPageTraceListener gbTraceListener = new WebPageTraceListener();
// Add the event log trace listener to the collection.
System.Diagnostics.Trace.Listeners.Add(gbTraceListener);

This programmatically adds a WebPageTraceListener to the trace listeners collection for your application.
5. In the same directory as Default.aspx, save the file as Global.aspx.
With these steps, you have added a WebPageTraceListener to the trace listeners collection for the application. Although
ASP.NET displays trace messages whenever tracing is enabled for a page, System.Diagnostics trace messages are written
only when the code in which the trace messages reside is compiled by using an explicit compiler switch—the TRACE switch. In
other words, if you do not explicitly compile the AuthorClass using the TRACE switch, you will not see the trace messages,
even with the WebPageTraceListener added.
You can configure your application to automatically compile using the TRACE switch, by adding a new section to your
Web.config file.
To compile your application automatically with trace enabled
1. Open the Web.config file for your application.
2. Place the following code into your Web.config file after the <system.diagnostics> section.

<system.codedom>
<compilers>
<compiler language="c#;cs;csharp"
extension=".cs"
compilerOptions="/d:TRACE"
type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.3500.0, C
ulture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="1" />
<compiler language="VB"
extension=".vb"
compilerOptions="/d:Trace=true"
type="Microsoft.VisualBasic.VBCodeProvider, System,
Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</compilers>
</system.codedom>

By default, this configuration section makes your application compile all modules with the TRACE option.
If you view the Default.aspx page now, you will see both ASP.NET and System.Diagnostics trace messages. If the ASP.NET and
System.Diagnostics trace messages do not appear, you might have to recompile the AuthorClass object.
From the trace information, you can see the AuthorClass object is created and its GetAuthors method is called during the
PreRender method of the Web page life cycle. You can also see that there is a significant time lag when the AuthorClass
object is created; the difference in time between the "Begin PreRender" message and the "AuthorClass is created." message is
significant. This is because the AuthorClass opens the Authors.xml file and initializes its DataSet during creation, which is a
relatively costly operation.
In the next section, you will learn how to configure your ASP.NET Web application to route all trace messages to the .NET
Framework tracing output.
Routing All Tracing Output to .NET Framework Tracing
You might want to route ASP.NET tracing messages to the standard output for Trace messages, which can be a console
window, disk, the Windows Event Log, or any other trace message output. You can enable this message routing in the
Web.config configuration file.
To route all ASP.NET trace messages to the system tracing output
1. Open the Web.config file for your application.
2. Add a new attribute, writeToDiagnosticsTrace, to the trace element under <system.web>, and then set
writeToDiagnosticsTrace to true.

<system.web>
<trace writeToDiagnosticsTrace="true"/>
<customErrors mode="Off"/>
</system.web>

This configuration attribute instructs ASP.NET tracing to route ASP.NET trace messages to the standard system tracing
output mechanism.
To view the ASP.NET and System.Diagnostics trace messages in a context outside an ASP.NET page, use a
TextWriterTraceListener object to write the trace messages to a file.
The TextWriterTraceListener object must be configured to write to a specific file. You can do this using the
initializeData attribute of the <add> Element for <listeners> for <trace>.
3. Use the same steps that you followed to add the WebPageTraceListener object in the second procedure in "Routing All
Tracing Output to the Web Form," earlier in this walkthrough, to add a TextWriterTraceListener object to your
Web.config file and configure the TextWriterTraceListener to write to a file in the application root directory named
Asptesttrace.log.
Assuming that you did not add a WebPageTraceListener programmatically in the Global.asax file, the
<system.diagnostics> section of the Web.config file will look similar to the following:

<system.diagnostics>
<trace autoflush="true">
<listeners>
<add name="WebPageTraceListener"
type="System.Web.WebPageTraceListener, System.Web, Version=2.0.3600.0, Culture
=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
<add name="TestTracer"
type="System.Diagnostics.TextWriterTraceListener, System, Version=2.0.3600.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089"
initializeData="<app root directory>\Asptesttrace.log" />
</listeners>
</trace>
</system.diagnostics>

Note
The initializeData attribute in the previous step has a placeholder value for the ASP.NET application root directory. If y
ou try to a write trace messages to a file other than your application root directory, you might receive a security excepti
on. By default, ASP.NET does not allow writing files to locations on disk that are outside the application root directory, s
uch as C:\. Additionally, you might have to grant Write permission to the trace log for the ASP.NET worker process acco
unt.

By default, you must wait to fill the trace buffer before trace data is written to the target stream.
4. To see trace data in the trace log immediately after requesting your ASP.NET page, flush the buffer with every trace write
by setting the autoflush attribute set to true as you did in the preceding step.
The default value for the autoflush attribute is false.
5. To flush the buffer of trace information programmatically, call the Flush method.
Note
For the business object that you developed in this walkthrough, if you call the Flush method in the Page_Load method
and the autoflush attribute is false, the trace log will not show the trace data because the business object is rendered
after the page Load event occurs.

Next Steps
This walkthrough illustrated how to work with ASP.NET and System.Diagnostics tracing features to route all trace messages a
single output. You might want to experiment more with trace listeners and output and ASP.NET instrumentation features. For
example, you might want to do the following:
Add an EventLogTraceListener object to your application.
To do this, you would add an EventLogTraceListener object either programmatically or by using the configuration file
that uses the same procedure as for the WebPageTraceListener. You can open the Event Log to review the trace
messages that your application writes to the Event Log.
Change the business component to work with database data instead of with an XML file. You do not need to make any
change to the controls on the page.
See Also
Concepts
Reading ASP.NET Trace Information
Application-Level ASP.NET Tracing Overview
Other Resources
ASP.NET Tracing
Visual Web Developer

Walkthrough: Copying a Web Site Using the Copy Web Site


Tool
This walkthrough shows you how to use the Copy Web Site tool to copy files between your current Web site and another Web
site.
During this walkthrough, you will learn how to do the following:
Copy files between Web sites.
Synchronize two Web sites so that they have the same version of each file.
Note
If you copy an application that contains a reference to a custom component that is registered in the GAC, the compone
nt will not be copied with the application. For more information, see
How to: Add a Reference to a .NET or COM Component in a Web Site.

Prerequisites
In order to complete this walkthrough, you will need the following:
Visual Web Developer
The .NET Framework
Creating the Shared Web Site
In this walkthrough you will work with both a shared and local Web site as you might in a production environment. A typical
scenario is that the shared Web site is on another server, such as a staging server or production server. When you want to
work on the site, you create a local version of the site, and then copy the files from the shared server to your computer. When
you have finished your updates, you copy the local files back to the shared server.
This walkthrough will also let you see what it might be like to work in an environment where there is more than one developer.
If there were other developers working on the site, they might also download files, edit them locally, and then copy the files
back to the shared server. Therefore, not only must you copy files from the local Web site to the shared Web site, but you also
might have to copy updated versions of files on the shared Web site to the local Web site.
This walkthrough emulates this scenario by having you create two Web sites. Instead of residing on separate computers, the
Web sites both reside on the local computer. This lets you work with the Copy Web Site tool as you would in a production
environment but without requiring you to use a second computer. All tasks that you perform in this walkthrough work
identically when the shared Web site is on another computer. You will emulate the edits made by other developers by using
Notepad to change files.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the left-most Location list, click File System, and then in the right-most Location list, enter C:\SharedWebSite.
Note
Procedures later in the walkthrough assume that you are working with a Web site named SharedWebSite.

5. In the Language list, click the programming language that you prefer to work in.
6. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating Test Pages
For this walkthrough, you will create some simple pages with known names.
Note
To test copying Web pages, it is not important that you have specific pages. However, later in the walkthrough you will edit t
he pages that you create in the next procedure.

To create test pages


1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
2. Under Visual Studio installed templates, click Web Form.
3. In the Name box, type Services.aspx.
4. In the Language list, click the programming language that you prefer to work in.
5. Click Add.
The new page appears in the editor.
6. Switch to Design view.
7. In the page, type Services, highlight to select the text that you just entered, and then on the Formatting toolbar, click
Heading 1 <H1>.
8. Position the pointer at the end of the text.
9. Press ENTER to create a new paragraph, and then type This page lists the services that we offer.
10. Save the page.
11. Repeat Steps 1 through 9 to create a page named Products.aspx with a heading of Products and the text This page
lists the products that we sell.
12. Open the Default.aspx page and switch to Design view.
13. In the page, type the heading Home and the text Welcome to our Web site.
Now you will add controls on the home page (Default.aspx) to link to the pages that you just created.
To add links on the Home page
1. Open the Default.aspx page and switch to Design view.
2. From the Standard group in the Toolbox, drag a Hyperlink control onto the page.
3. Set Text to Products and NavigateUrl to ~/Products.aspx.
4. Drag another Hyperlink control onto the page, and then set Text to Services and NavigateUrl to ~/Services.aspx.
5. Save your files.
Testing the Web Site
Now you will test that the Web site works as you expect.
To test the Web site
1. In Solution Explorer, right-click Default.aspx, and then click View in Browser.
The page appears in the browser.
2. Click Products and Services to confirm that the links work.
3. Close the browser.
Creating the Source Web Site
In this part of the walkthrough, you will create a second Web site that you can use to copy files to and from. As explained in
"Creating the Shared Web Site," earlier in this walkthrough, both Web sites are on your computer, but the first Web site
functions as the shared Web site. The Web site that you will create in this part of the walkthrough functions as the site that you
would use to edit files.
To create the source Web site
1. On the File menu, click Close Project to close SharedWebSite.
2. On the File menu, click New Web Site.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the left-most Location list, click File System, and then in the right-most Location list, enter C:\LocalWebSite.
5. Click OK.
Copying Files from the Shared to the Local Web Site
At this point, a shared Web site exists on your computer and you have a new Web site open. If you were a new developer on a
project, you would first want to obtain all files from the shared Web site and copy the files to your local Web site.
To copy all files from the shared Web site to the local Web site
1. On the Website menu, click Copy Web Site.
The Copy <Websitename> tool appears.
2. Click Connect.
The Open Web Site dialog box appears.
3. Click File System.
4. In the Folder box, type C:\SharedWebSite.
If the shared site were on another computer, you would type the URL of the server.
5. Click Open.
The files from the shared site are listed under Remote Web Site.
Many of the files have symbols next to them that indicate their status. The arrow symbol shows you the direction that a
file will be copied if you synchronize the sites. Currently, the Services.aspx and Products.aspx files in the Remote Web
Site list point to the Source Web Site list, because if you synchronize the Web sites, the Services.aspx and Products.aspx
files will be copied from the shared site to the local site.
The Default.aspx files have question marks (?) next to them. This indicates that the file has the same name in both sites,
but different timestamp data and no information about the last time the files were copied.
6. Under Remote Web site, highlight to select all files and folders.
In this case, you want to obtain copies of all files from the shared site. You are emulating a scenario where you are a new
developer on an existing Web site and you want to obtain the most current versions of the Web site files. Because you
have created a new local site, you do not have to copy any files from the local site to the shared site.
7. Click the left-arrow button to copy the selected files from the shared site to the local site.
The left-arrow button is not labeled unless you move the pointer over it, in which case a ToolTip appears. The arrow is
pointing to Source Web Site.
Visual Web Developer starts copying files. When it gets to the Default.aspx file, it prompts you for confirmation to
overwrite the local copy of the file with the file from the shared site.
8. In the Confirm File Overwrite dialog box, select the Apply to all check box, and then click Yes.
In this case, it is safe to overwrite all local versions of any files that have duplicated file names, because you want the file
versions from the shared site. When the copy process is finished, the lists in Source Web Site and Remote Web Site
are the same.
Note
The Copy Web Site tool does not merge files, it only overwrites files.

Copying Individual Pages


You can use the Copy Web Site tool to copy all files or individual files. In this part of the walkthrough, you will create a new
Web page in the source Web site, and then copy the new Web page file to the shared Web site.
To create and copy an individual file
1. In Solution Explorer, right-click the name of the Web site, and then click Add New Item.
2. Under Visual Studio installed templates, click Web Form.
3. In the Name box, type Extra.aspx.
4. Click Add.
You do not have to add any content to the page.
5. Close the page.
The new page is displayed in Source Web Site with arrows next to it pointing to Remote Web Site. If you synchronize
right now, the files will be copied from the local Web site to the shared Web site.
6. On the Copy Web tab, highlight to select the new page or pages.
7. Click the right/left-arrow button to copy the selected files from the local Web site to the shared Web site.
This button is not labeled unless you move the pointer over it, in which case a ToolTip appears.
The new page is copied to the shared Web site and the list in Remote Web Site is updated.
Synchronizing Web Sites
Synchronizing means copying the most current version of each file so that both Web sites have the same copies of all files. Use
synchronization, if the files on the shared Web site might be updated by someone other than you. In this part of the
walkthrough, you will first change both the local and shared Web site, and then you will synchronize the changes between the
sites.
To change the local and shared Web sites
1. On the Copy <Websitename> tab, under Source Web site, click Extra.aspx, and then click the delete button.
2. When prompted for confirmation to delete the file, click Yes.
The files for the deleted page appear in Source Web Site with a symbol next to them, which indicates that the files have
been deleted.
Note
Make sure that the Show deleted files since the last copy operation check box is selected.

3. In Windows, start Notepad, and then open C:\SharedWebSite\Products.aspx.


4. Add extra spaces or other characters to the file, save the file, and then close Notepad.
You are changing the file to emulate what would occur if another developer changed the file on the shared Web site.
5. In Visual Web Developer, on the Copy <Websitename> tab, click Refresh Remote Web Site.
An arrow appears next to the Products.aspx file pointing to Source Web Site.
6. Under Remote Web Site, highlight to select all files and folders, and then click the synchronize button to synchronize
the selected file between the same relative paths in both LocalWebSite and SharedWebSite.
This button is not labeled unless you move the pointer over it. The button has a right and left arrow to indicate both
panes.
7. When prompted to delete the Extra.aspx file in the remote Web site, which in effect is propagating the deletion to the
remote Web site, click Yes.
The Products.aspx page is copied from the remote Web site to the source Web site.
Note
If you selected all files and folders under Source Web Site and synchronized the files and folders, the results would be
the same.

Next Steps
This walkthrough has illustrated the basic tasks that you can accomplish with the Copy Web Site tool. Although the Web sites
that you worked with contained only a few files, you can apply the techniques that are used in this walkthrough to sites of any
size. You might also want to experiment with additional ways to copy files to remote computers. For example, you might want
to do the following:
Work with an FTP Web site, which lets you open and edit files directly on a server that is configured to allow FTP
connections.
For detailed information, see Walkthrough: Editing Web Sites with FTP in Visual Web Developer.
Learn how to publish Web sites, which precompiles the contents of the Web site. You can then deploy the output to your
production server.
For detailed information, see Walkthrough: Publishing a Web Site.
See Also
Concepts
Web Site Deployment in Visual Web Developer
Copying Web Sites with the Copy Web Site Tool
Visual Web Developer

Walkthrough: Publishing a Web Site


Provides step-by-step instructions for using the Publish Web Site utility of the Microsoft Visual Web Developer Web
development tool to compile a Web site, and then copy the output to an active Web site.
If you want to deploy a finished Web site to a server, you can use the Publish Web Site utility that is included with the Microsoft
Visual Web Developer Web development tool. The Publish Web Site utility precompiles the pages and code that are in the Web
site and writes the compiler output to a folder that you specify. You can then copy the output to the target Web server and run
the application from there.
Note
The Publish Web Site utility is not available in Visual Web Developer Express edition.

Tasks illustrated in this walkthrough include the following:


Using the Publish Web Site utility to create precompiled output.
Prerequisites
In order to complete this walkthrough, you will need the following:
Visual Web Developer.
The Visual Web Developer Express edition does not support the Publish Web Site utility.
Access to Microsoft Internet Information Services (IIS) so that you can test the result of publishing a Web site.
In this walkthrough, it is assumed that you have IIS running on your own computer. Alternatively, you can use any
instance of IIS for which you have permission to create a virtual directory.
Creating the Web Site
If you have already created a Web site in Visual Web Developer by completing
Walkthrough: Creating a Basic Web Page in Visual Web Developer, you can use that Web site and go to the next section.
Otherwise, create a new Web site and page by following these steps.
For this walkthrough, you will create a file system Web site.
To create a file system Web site
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. In the left-most Location list, click File System.
5. In the right-most Location list, enter the name of the folder where you want to keep the pages of the Web site.
For example, type the folder name C:\WebSites.
6. In the Language list, click the programming language that you prefer to work in.
7. Click OK.
Visual Web Developer creates the folder and a new page named Default.aspx.
Creating a Test Page and Class
For this walkthrough, you will create a Web page with some controls. You will also create a class file that you will use in the
Web page. Creating both a Web page and a separate class will let you see how the publish process precompiles the contents of
the Web site.
You will start by creating a new page, and then adding a button and label to the page.
To create the page and add controls
1. In Solution Explorer, right-click the name of the Web site and click Add New Item.
2. Under Visual Studio installed templates, click Web Form.
3. In the Name box, type SamplePage.aspx.
4. In the Language list, click the programming language that you prefer to work in.
5. Click Add.
6. Switch to Design view.
7. From the Standard group in the Toolbox, drag a Label control onto the page.
8. From the Standard group in the Toolbox, drag a Button control onto the page and position it next to the Label control.
Next, you will create the source code for a simple class that has a single property in it. You will use the class in the code for
your page.
To create a class
1. In Solution Explorer, right-click the name of the Web site, point to Add ASP.NET Folder, and then click App_Code.
A new folder named App_Code appears in your application in Solution Explorer. The App_Code folder is a special
reserved ASP.NET application folder. For more information, see ASP.NET Web Site Layout.
2. Right-click the App_Code folder, and then click Add New Item.
3. Under Visual Studio installed templates, click Class.
4. In the Name box, type TestClass.
5. In the Language list, click the programming language that you prefer to work in.
Note
The programming language that you select does not have to be the same as the programming language that you use i
n the .aspx page.

6. Click Add.
Visual Web Developer creates a skeleton class file in the programming language that you have specified. Notice that the
extension of the class file name matches the language that you have selected. For example, if you are creating a class in
Microsoft Visual Basic, the file name extension is .vb.
7. Create a property named TestProperty.
When you are finished, the complete class file will look similar to the following:
VB
Imports Microsoft.VisualBasic
Public Class TestClass
Private TestPropertyValue As String
Public Property TestProperty() As String
Get
Return TestPropertyValue
End Get
Set(ByVal value As String)
TestPropertyValue = value
End Set
End Property
End Class

C#
using System;
public class TestClass
{
public TestClass() { }
private string TestPropertyValue;
public string TestProperty
{
get{ return TestPropertyValue; }
set{ TestPropertyValue = value; }
}
}

Now, you can use the class in the page. Notice that you do not have to compile the class file before using it.
To use the class in the page code
1. Open SamplePage.aspx and switch to Design view.
2. Double-click the Button control to create a Click handler for it.
3. In the Click handler, create an instance of the TestClass that you created in the preceding procedure, assign a value to
the TestProperty property, and then display the TestProperty value in the Label control.
The complete code will look similar to this:
VB
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
Dim testClass As New TestClass
testClass.TestProperty = "Hello"
Label1.Text = testClass.TestProperty
End Sub

C#
protected void Button1_Click(object sender, EventArgs e)
{
TestClass testClass = new TestClass();
testClass.TestProperty = "Hello";
Label1.Text = testClass.TestProperty;
}

Testing the Site


Before publishing the site, you can test it to make sure that the site works in the way that you expect.
To test the Web site
1. Open the SamplePage.aspx page.
2. Press CTRL+F5.
The page appears in the browser.
3. Click Button and make sure that text appears in the Label control.
4. Close the browser.
Publishing the Web Site
Now that you have a Web site, you can publish it. You can publish the Web site to any location that you have access to on the
local computer or on a network that is using any connection protocol that is supported by Visual Web Developer. You have the
following options for copying the Web site:
Use a UNC share to copy to a shared folder that is on another computer on the network.
Use FTP to copy to a server.
Use the HTTP protocol to copy to a server that supports FrontPage 2002 Server Extensions from Microsoft.
In this part of the walkthrough, you will publish the Web site to local folder.
To publish the Web site
1. On the Build menu, click Publish Web Site.
The Publish Web Site dialog box appears.
2. In the Target Location box, enter c:\CompiledSite.
Caution
All data in the target folder and its subfolders will be deleted. Make sure that you do not type the name of a folder that
contains data or contains subfolders with data.

For the purposes of this walkthrough, you are publishing to a local folder. You could also publish to a UNC share. If you
wanted to publish to a remote Web site using HTTP or FTP, the Target Location box is where you would specify the
remote server URL.
The Allow this precompiled site to be updatable option specifies that all program code is compiled into assemblies,
but that .aspx files (including single-file ASP.NET Web pages) are copied as-is to the target folder. In this walkthrough,
you will not select that option. For detailed information, see Publishing Web Sites.
3. Click OK.
Visual Web Developer precompiles the contents of the Web site and writes the output to the folder that you specified.
The Output window displays progress messages. If an error occurs during compilation, it is reported in the Output
window.
4. If errors occur during publishing, fix the errors, and then repeat step 1.
Examining the Output of the Publish Web Site Command
It is useful to examine the output of the Publish Web Site command so that you can see what Visual Web Developer has done
with your Web site files.
To examine the output of the Publish Web Site command
1. In Windows Explorer, move to the folder that you specified as the target for the Publish Web Site command.
2. Using a text editor, such as Notepad, open the SamplePage.aspx file.
Notice that the file does not contain the markup that you originally had in the file. Instead, the .aspx page is only a
placeholder that can be used as part of a URL.
3. Move to the Bin folder.
The folder contains two types of files:
.compiled files, which correspond to pages.
.dll files, which contain the executable code for the Web site, such as the class file that you created.
Remember that the page, its code, and the separate class file that you created have all been compiled into executable code.
Testing the Published Web Site
You can now test the published Web site by running it.
To test the published Web site
1. Create an IIS virtual directory that points to the target folder.
You can use the IIS administrative tools or alternatively, use the following steps:
a. In Windows Explorer, right-click the name of the target folder, and then click Sharing and Security.
b. On the Web Sharing tab, click Share this Folder.
The Edit Alias dialog box appears.
c. If you want, change the name of the alias.
The default permissions allow Read access and allow Scripts, such as ASP.NET pages, to run.
d. Click OK to close the Edit Alias dialog box, and then click OK to close the Properties dialog box.
2. Open the browser and type the following URL:
http://localhost/CompiledSite/SamplePage.aspx
The SamplePage.aspx page appears. However, this time you are viewing the version of the page that was created by the
precompiler for deployment.
Next Steps
This walkthrough has shown you the basic procedure for publishing a precompiled Web site. Suggestions for more exploration
include the following:
Experiment with using the Copy Web tool instead, which copies the Web site as-is (as source code) to a target folder.
For more information, see Copying Web Sites with the Copy Web Site Tool.
Publish the Web site to a remote IIS Web site.
See Also
Tasks
Walkthrough: Copying a Web Site Using the Copy Web Site Tool
Concepts
Web Site Deployment in Visual Web Developer
Publishing Web Sites
Visual Web Developer

How Do I in Visual Web Developer


How Do I is your gateway to key topics about creating dynamic Web sites with Visual Web Developer. The essential
information on working with Visual Web Developer is listed in this topic. The links provide pointers to important procedure-
based Help pages.
Getting Started
Overview ... Guided Tour
Development Environment
Web page designer ... editing HTML ...
Web Sites
Creating ... site navigation ... themes ... accessibility ... globalization ... more
Web Pages
Programming pages ... master pages ... themes ... Web Parts ... client script ... caching ...
Web Page Controls
Standard controls, data controls, navigation controls ...
Data
Displaying data ... editing data ... master/detail pages ...
Security
Security practices ... membership (authentication) ...
Troubleshooting
Debugging ... tracing ... error handling ...
Globalization
Resources ... encoding ... bi-directional text ...
Deployment
Copying Web sites ... compiling and publishing Web sites ...
See Also
Other Resources
Visual Web Developer
Visual Web Developer

Data (How Do I in Visual Web Developer)


This page links to help on widely used tasks for displaying and editing data in ASP.NET Web pages. To view other categories of
popular tasks covered in Help, see How Do I in Visual Web Developer.
The information in this topic is subdivided into the following sections:
Getting Started
Walkthroughs
SQL-based Databases
Business Objects
XML
Data Controls
Data Security
Getting Started
ASP.NET Data-Bound Web Server Controls Overview
Provides information on using controls to display data on ASP.NET Web pages.
Data Source Controls Overview
Provides information on using declarative controls (data source controls) on ASP.NET Web pages to connect to data sources
and read and write data.
Binding to Data Using a Data Source Control
Provides information on how to associate display controls on the page with data source controls that perform data access.
Using Parameters with Data Source Controls
Provides information on passing run-time information for search and update to data source controls.
Sorting Data with Data Source Controls
Provides information on how to configure data source controls to sort data.
Modifying Data using Data Source Controls
Provides information on how to configure data source controls to update or delete records in a data source.
Filtering Data Using Data Source Controls
Provides information on how to configure data source controls to create subsets of the data returned by the data source
control.
Caching Data Using Data Source Controls
Provides information on how to configure data source controls to store data in memory for faster performance.
Walkthroughs
Walkthrough: Basic Data Access in Web Pages
Provides a tutorial on how to use the GridView control and SqlDataSource controls to display data on an ASP.NET Web
page.
Walkthrough: Displaying Data Using a Stored Procedure in the GridView Web Server Control
Provides a tutorial on using a SQL Server stored procedure to retrieve data.
Walkthrough: Creating a Web Page to Display Access Database Data
Provides a tutorial on how to use the GridView control and AccessDataSource controls to display data from a Microsoft
Access database on an ASP.NET Web page.
Walkthrough: Creating Master/Detail Web Pages in Visual Studio
Provides a tutorial on how to use the DropDownList, GridView, DetailsView, and SqlDataSource controls to create pages
that display lists of data where the user can select an individual record to examine further.
Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control
Provides a tutorial on using a DetailsView control to enable users to edit existing records and create new ones.
Walkthrough: Data Binding to a Custom Business Object
Provides a tutorial on how to use the ObjectDataSource control to create multi-tier data access in an ASP.NET Web
application.
Walkthrough: Data Binding Web Pages with a Visual Studio Data Component
Provides a tutorial on how to use Visual Studio tools to create a data-access object that you can use with the
ObjectDataSource control.
Walkthrough: Displaying and Formatting Data with the DataList Web Server Control
Provides a tutorial on creating a DataList control, which enables you to display data in an HTML table using a layout you
define.
Walkthrough: Displaying Formatted Data in Web Pages with the FormView Web Server Control
Provides a tutorial on using a FormView control to display a single record at a time, using free-form layout templates that
you define.
Walkthrough: Displaying a Drop-Down List While Editing in the GridView Web Server Control
Provides a tutorial on how to customize the GridView control to display a drop-down list in edit mode.
Walkthrough: Simple Sorting for the GridView Web Server Control
Provides a tutorial on how to use built-in features of the GridView control to enable users to sort the displayed data.
Walkthrough: Creating a Web Page to Display XML Data
Provides a tutorial on using the XmlDataSource control to read XML data and the GridView and DropDownList controls
to display the XML data on a page.
Walkthrough: Displaying Hierarchical Data in a TreeView Control
Provides a tutorial on using the TreeView control to display XML data.
Walkthrough: Displaying an XML Document in a Web Forms Page Using Transformations
Provides a tutorial on using the Xml control to display the contents of an XML document on a page.
Walkthrough: Using ASP.NET Output Caching with SQL Server
Provides a tutorial on caching pages that are removed from the cache only when their dependent data in SQL Server
changes.
SQL-based Databases
How to: Connect to a SQL Server Database Using the SqlDataSource Control (Visual Studio)
Provides steps for creating a connection string that can be used to access a SQL Server database.
How to: Connect to an Oracle Database Using the SqlDataSource Control (Visual Studio)
Provides steps for reading and writing data in an Oracle database.
How to: Connect to an ODBC Database Using the SqlDataSource Control (Visual Studio)
Provides steps for reading and writing data in any ODBC-compliant database.
How to: Enable Filtering for the SqlDataSource Control
Provides information on how to configure a SqlDataSource control to create subsets of the data returned by the data
source control.
Selecting Data Using the SqlDataSource Control
Provides information on how to configure a SqlDataSource control to run database queries to return data.
Modifying Data using the SqlDataSource Control
Provides information on how to configure a SqlDataSource control to update or delete in a database.
Using Parameters with the SqlDataSource Control
Provides information on passing run-time information for search and update to a SqlDataSource control.
Caching Data with the SqlDataSource Control
Provides information on how to configure a SqlDataSource control to store data in memory for faster performance.
How to: Connect to an Access Database Using the SqlDataSource Control (Visual Studio)
Provides steps for reading and writing data in a Microsoft Access database.
Retrieving Data Using the AccessDataSource Web Server Control
Provides steps for creating a connection string that can be used to open a Microsoft Access database.
Business Objects
Walkthrough: Data Binding to a Custom Business Object
Provides a tutorial on how to use the ObjectDataSource control to create multi-tier data access in an ASP.NET Web
application.
Walkthrough: Data Binding Web Pages with a Visual Studio Data Component
Provides a tutorial on how to use Visual Studio tools to create a data-access object that you can use with the
ObjectDataSource control.
Creating an ObjectDataSource Control Source Object
Provides information on creating a class that can be used as a middle-tier object accessible by the ObjectDataSource
control.
Using Parameters with the ObjectDataSource Control
Provides information on configuring parameter objects so you can pass update, delete, paging, and sorting information to an
ObjectDataSource control.
XML
Walkthrough: Creating a Web Page to Display XML Data
Provides a tutorial on using the XmlDataSource control to read XML data and the GridView and DropDownList controls
to display the XML data on a page.
Filtering Data Using the XmlDataSource Control
Provides information on using XPath queries in the XmlDataSource control to find subsets of XML data.
Binding a Tabular Control to the XmlDataSource Control
Provides information on reading XML data using the XmlDataSource control and displaying it in a control such as the
GridView control.
Walkthrough: Displaying Hierarchical Data in a TreeView Control
Provides a tutorial on using the TreeView control to display XML data.
How to: Add XML Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating an Xml control using the Visual Web Developer designer. This control enables you to display an
XML document on the page.
How to: Load XML Data in the XML Web Server Control
Provides steps for configuring an Xml control to display an XML document or XML stream.
How to: Transform XML Data in the XML Web Server Control
Provides steps for using a transformation with the Xml control to customize the display of XML data.
Data Controls
How to: Add DataList Web Server Controls to an ASP.NET Web Page (Visual Studio)
Provides steps for creating a DataList control, which enables you to display data in an HTML table using a layout you define.
Walkthrough: Displaying and Formatting Data with the DataList Web Server Control
Provides a tutorial on creating a DataList control, which enables you to display data in an HTML table using a layout you
define.
How to: Allow Users to Delete Items in DataList Web Server Controls
Provides steps for configuring the DataList control to enable users to delete data records.
How to: Allow Users to Edit Items in DataList Web Server Controls
Provides steps for configuring the DataList control to enable users to edit data records.
How to: Allow Users to Select Items in DataList Web Server Controls
Provides steps for configuring the DataList control to enable users to select (highlight) a specific item.
How to: Customize Items Dynamically in the DataList Web Server Control
Provides steps for how to use code to change the look or behavior of items in a DataList control at run time.
How to: Specify Flow or Table Format in DataList Web Server Controls
Provides steps for how to set the layout of a DataList control.
How to: Specify Horizontal or Vertical Layout in DataList Web Server Controls
Provides steps for how to set the layout of a DataList control.
Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control
Provides a tutorial on using a DetailsView control to enable users to edit existing records and create new ones.
Modifying Data Using a DetailsView Web Server Control
Provides information on using the DetailsView control to enable users to edit data one record at a time.
Paging in a DetailsView Web Server Control
Provides information on configuring the DetailsView control to enable users to page through multiple records, one at a
time.
Walkthrough: Displaying Formatted Data in Web Pages with the FormView Web Server Control
Provides a tutorial on using a FormView control to display a single record at a time, using free-form layout templates that
you define.
Modifying Data Using a FormView Web Server Control
Provides steps on using a FormView control to enable users to edit data one record at a time.
Paging in a FormView Web Server Control
Provides information on configuring the FormView control to enable users to page through multiple records, one at a time.
Walkthrough: Creating Master/Detail Web Pages in Visual Studio
Provides a tutorial on how to use the DropDownList, GridView, DetailsView, and SqlDataSource controls to create pages
that display lists of data where the user can select an individual record to examine further.
Walkthrough: Simple Sorting for the GridView Web Server Control
Provides a tutorial on how to use built-in features of the GridView control to enables users to sort the displayed data.
How to: Customize Controls for Editing in the GridView Web Server Control
Provides steps on configuring the GridView control to display the controls that you choose when in edit mode.
How to: Set GridView Web Server Control Column Width Dynamically
Provides steps for setting column widths in the GridView control according to the width of the data being displayed.
How to: Respond to Button Events in Data-Bound Controls
Provides steps for how to handle events raised by button controls in list data controls such as the GridView, DataList, and
Repeater controls.
How to: Enable Default Deleting in the GridView Web Server Control
Provides steps for configuring the GridView control to enable users to delete data records.
How to: Enable Default Editing in the GridView Web Server Control
Provides steps for configuring the GridView control to enable users to edit data records.
How to: Enable Default Paging in the GridView Web Server Control
Provides steps for configuring the GridView control to enable users to page through long lists of data records.
Walkthrough: Data Binding to a Custom Business Object
Provides a tutorial on how to use the ObjectDataSource control to create multi-tier data access in an ASP.NET Web
application.
Walkthrough: Data Binding Web Pages with a Visual Studio Data Component
Provides a tutorial on how to use Visual Studio tools to create a data-access object that you can use with the
ObjectDataSource control.
How to: Add Repeater Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a Repeater control, which enables you to display data on an ASP.NET Web page using free-form
layout templates that you define.
How to: Enable Filtering for SqlDataSource Controls (Visual Studio)
Provides steps for how to configure a SqlDataSource control to enable the results of a query to be further refined with
filtering.
How to: Respond to Button Events in DataList, Repeater, or GridView Items
Provides steps for how to handle events raised by button controls in list data controls such as the GridView, DataList, and
Repeater controls.
How to: Create Web Server Control Templates Using the Designer
Provides steps for using the Visual Web Developer designer to create and edit templates in the GridView, DetailsView,
FormView, DataList, and Repeater controls.
How to: Create ASP.NET Web Control Templates Declaratively
Provides steps for creating templates in the GridView, DetailsView, FormView, DataList, and Repeater controls by editing
the markup directly.
How to: Bind to Data in a Templated Control
Provides steps for adding data-bound controls to templates in controls such as the GridView, DetailsView, FormView,
DataList, and Repeater controls.
Data Security
Securing Data Access
Provides guidelines for improving the security of data access in ASP.NET Web applications.
How To: Secure Connection Strings when Using Data Source Controls (Visual Studio)
Provides steps for encrypting connection strings for database access.
How to: Access SQL Server as a Local User
Provides steps for configuring your application to log into SQL Server on the same computer as the Web server.
How to: Access SQL Server Using a Mapped Windows Domain User
Provides steps for configuring your application to log into SQL Server using a specific Windows user account.
How to: Access SQL Server Using Predetermined Credentials
Provides steps for configuring your application to log into SQL Server using a user name and password that you build into
your application.
How to: Access SQL Server Using Windows Integrated Security
Provides steps for configuring your application to log into SQL Server with the user's current Windows user account
information.
See Also
Concepts
How Do I in Visual Web Developer
Visual Web Developer

Deployment (How Do I in Visual Web Developer)


This page links to help on widely used tasks for copying a Web site from your computer to another computer such as a Web
server. To view other categories of popular tasks covered in Help, see How Do I in Visual Web Developer.
Walkthroughs
Walkthrough: Copying a Web Site Using the Copy Web Site Tool
Provides a tutorial on creating a Web site and copying the files to a production Web server.
Walkthrough: Editing Web Sites with FTP in Visual Web Developer
Provides a tutorial on using FTP to open a Web site on a remote Web server.
Walkthrough: Publishing a Web Site
Provides a tutorial on compiling a Web site into assemblies that can be deployed to a Web server.
Deploying
How to: Copy Web Site Files with the Copy Web Site Tool
Provides steps for how to copy files from your computer to a Web server or vice versa.
Web Site Deployment in Visual Web Developer
Provides an overview of options for deploying a Web site to a Web server.
How to: Publish Web Sites (Visual Studio)
Provides steps for how to create a compiled version of a Web site that can be copied to a Web server.
FTP
FTP-Deployed Web Sites
Provides an overview of what FTP is and how it is supported in Visual Studio.
How to: Create and Configure FTP Sites in IIS
Provides steps for how to set up a Web server with Internet Information Services (IIS) to accept FTP connections.
See Also
Concepts
How Do I in Visual Web Developer
Visual Web Developer

Development Environment (How Do I in Visual Web Developer)


This page links to help on widely used information pertaining to using the Visual Web Developer integrated design
environment (IDE). To view other categories of popular tasks covered in Help, see How Do I in Visual Web Developer.
What's New in Web Development for Visual Studio
Provides information on changes and enhancements in the Web development features of Visual Web Developer.
What's New in the Web Page Designer and Editors
Provides information on changes and enhancements in Visual Web Developer for creating and editing ASP.NET Web pages.
What's New in Code-Behind Support in Visual Web Developer
Provides information on changes and enhancements in Visual Web Developer to support creating page code.
Web Solution and Project File Conversion
Provides details about changes made to pages and to other files during conversion.
Visual Web Developer Settings
Provides information on the default IDE settings.
Walkthroughs
Walkthrough: Creating a Basic Web Page in Visual Web Developer
Provides a tutorial on creating and editing an ASP.NET Web page in Visual Web Developer, including an overview of the Web
development environment.
Walkthrough: Creating a Basic Web Page with Code Separation in Visual Web Developer
Provides a tutorial on how to work with ASP.NET code-behind pages in the Visual Web Developer designer.
Walkthrough: Basic HTML Editing in Visual Web Developer
Provides a tutorial on working with markup (HTML) in the Visual Web Developer designer.
Walkthrough: Advanced HTML Editing in Visual Web Developer
Provides a tutorial on additional HTML editing features in the Visual Web Developer designer.
Walkthrough: Editing HTML Tables in Visual Web Developer
Provides a tutorial on adding and editing HTML tables in the Visual Web Developer designer.
Walkthrough: Working with Cascading Style Sheet Styles in Visual Web Developer
Provides a tutorial on features in the Visual Web Developer designer that help you create styles and cascading style sheets.
Walkthrough: Code Editing in Web Pages in Visual Web Developer
Provides a tutorial on features of the code editor in the Visual Web Developer designer that help you create code quickly and
accurately.
Creating Web Sites and Pages
How to: Add ASP.NET Web Pages to a Web Site (Visual Studio)
Provides steps for creating ASP.NET Web pages using Visual Web Developer.
How to: Create Scripts and Edit Event Handlers
Provides steps for writing client script while working in Source view of the Visual Web Developer designer.
How to: Display Hidden Information in Design View
Provides steps for setting options to show or hide editing aids such as glyphs and borders around non-visible elements.
How to: Position Elements in Design View
Provides steps for setting positioning options for elements in Design view, so that you can drag them to specific locations on
the page.
How to: Test Web Pages in Visual Web Developer
Provides steps for how to run your Web pages to test them while working in the Visual Web Developer designer.
How to: Specify Start Pages for Testing Web Sites in Visual Web Developer
Provides steps for how to select a specific page to run when testing your Web site in the Visual Web Developer designer.
How to: Add Web Browsers to Visual Web Developer
Provides steps for how to configure Visual Web Developer to use alternative browsers for testing.
Editing HTML Elements and Cascading Style Sheets
How to: Create and Edit HTML Tables in Design View
Provides steps for using the Visual Web Developer designer to create HTML tables.
How to: Select HTML Table Elements and Contents in Visual Web Developer
Provides steps for using the Visual Web Developer designer to select specific rows, columns, or cells in an HTML table.
How to: Resize HTML Table Elements in Visual Web Developer
Provides steps for using the Visual Web Developer designer to resize rows, columns, or cells in HTML tables.
How to: Add and Remove HTML Table Elements in Visual Web Developer
Provides steps for using the Visual Web Developer designer to create or remove rows, columns, or cells in HTML tables.
HTML Table Editing Tips in Visual Web Developer
Provides information on common issues that arise when working with HTML tables in Design view.
How to: Navigate in the HTML Editor in Visual Web Developer
Provides steps for using editor features such as the tag navigator to quickly move to specific elements in a page.
How to: Collapse and Expand HTML Elements in Visual Web Developer
Provides steps for using editor features in Source view to make large elements (such as tables) into units you can hide or
display as required.
How to: Insert HTML Hyperlinks and Bookmarks in Design View
Provides steps for creating links (a tags) in Design view.
Markup Validation in Visual Web Developer
Provides information on how the editor can help you find markup elements that do not conform to a specific schema, such
as XHTML 1.0.
How to: Set Validation Options for HTML Editing in Visual Web Developer
Provides steps for customizing the behavior of markup validation.
How to: Select Validation Schemas for HTML Editing in Visual Web Developer
Provides steps for configuring the editor to use a specific schema, such as XHTML 1.0, when validating markup in Source
view.
XHTML in Visual Web Developer
Provides information on XHTML support in Visual Web Developer.
How to: Choose an Alternate HTML Editor in Visual Web Developer
Provides steps for selecting the HTML editor of your choice for use in Visual Web Developer.
How to: Create External Cascading Style Sheets (Visual Studio)
Provides steps for creating a .css file that you can link to pages in your Web site.
How to: Link Cascading Style Sheets to ASP.NET Web Pages (Visual Studio)
Provides steps for applying a .css file to a page.
How to: Add Cascading Style Sheet Attributes in Design View
Provides steps for adding style blocks or style attributes for individual elements.
See Also
Concepts
How Do I in Visual Web Developer
Visual Web Developer

Getting Started (How Do I in Visual Web Developer)


This page links to a selection of walkthroughs (tutorials) that provide an overview of creating Web sites and ASP.NET Web
pages using Visual Web Developer. To view other categories of popular tasks covered in Help, see
How Do I in Visual Web Developer.
What's New in Web Development for Visual Studio
Provides information on changes and enhancements in the Web development features of Visual Web Developer.
Basic Techniques
Walkthrough: Creating a Basic Web Page in Visual Web Developer
Provides a tutorial on creating and editing an ASP.NET Web page in Visual Web Developer, including an overview of the Web
development environment.
Walkthrough: Creating a Basic Web Page with Code Separation in Visual Web Developer
Provides a tutorial on how to work with ASP.NET code-behind pages in the Visual Web Developer designer.
Walkthrough: Basic HTML Editing in Visual Web Developer
Provides a tutorial on working with markup (HTML) in the Visual Web Developer designer.
Working with Data
Walkthrough: Basic Data Access in Web Pages
Provides a tutorial on how to use ASP.NET data controls to display data on an ASP.NET Web page.
Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control
Provides a tutorial on using ASP.NET controls to enable users to edit existing records and create new ones.
Walkthrough: Creating Master/Detail Web Pages in Visual Studio
Provides a tutorial on how to use ASP.NET data controls to create pages that display lists of data where the user can select an
individual record to examine further.
Walkthrough: Data Binding to a Custom Business Object
Provides a tutorial on how to use ASP.NET data controls to create multi-tier data access in an ASP.NET Web application.
Customizing Web Sites and Pages
Walkthrough: Creating a Web Site with Membership and User Login (Visual Studio)
Provides a tutorial on adding Web site security using ASP.NET features to add a login page, authentication, and authorization.
Walkthrough: Customizing a Web Site Using Themes in Visual Studio
Provides a tutorial on creating a consistent look for pages in your Web site.
Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer
Provides a tutorial on creating a consistent layout for pages in your Web site.
Walkthrough: Creating a Web Parts Page in Visual Web Developer
Provides a tutorial on creating ASP.NET Web pages that users can customize using their browser.
Walkthrough: Creating Reusable Elements with ASP.NET User Controls
Provides a tutorial on using the Visual Web Developer designer to create a composite control that you can add to any
ASP.NET Web page.
Walkthrough: Adding Site Navigation to a Web Site
Provides a tutorial on using site maps and creating navigation using a menu, a tree view, and a site map path control
(sometimes referred to as a breadcrumb).
Walkthrough: Creating a Web Site with Membership and User Login (Visual Studio)
Provides a tutorial on using login controls to add a login page, authentication, and authorization.
Managing Web Sites
Walkthrough: Editing Web Sites with FTP in Visual Web Developer
Provides a tutorial on creating a Web site in a local folder on your computer and testing it using the ASP.NET Development
Server.
Walkthrough: Maintaining Web Site User Information with Profile Properties
Provides a tutorial on using ASP.NET profiles to gather information from users and store it for use each time they visit.
Walkthrough: Debugging Web Pages in Visual Web Developer
Provides a tutorial on using the integrated debugger in the Visual Web Developer designer to find errors in your code.
Walkthrough: Copying a Web Site Using the Copy Web Site Tool
Provides a tutorial on synchronizing local and remote versions of a Web site.
Walkthrough: Using Output Caching to Enhance Web Site Performance
Provides a tutorial on storing pages and application data in memory for faster performance.
Walkthrough: Using Resources for Localization with ASP.NET
Provides a tutorial on creating Web pages that can display information in different languages.
See Also
Concepts
How Do I in Visual Web Developer
Visual Web Developer

Globalization (How Do I in Visual Web Developer)


This page links to help on widely used tasks for creating Web pages that can be used with different languages and cultures. To
view other categories of popular tasks covered in Help, see How Do I in Visual Web Developer.
Walkthroughs
Walkthrough: Using Resources for Localization with ASP.NET
Provides a tutorial on creating Web pages that can display information in different languages.
Resources
ASP.NET Web Page Resources Overview
Provides information on using resource files (.resx files) to store language-specific and locale-specific text.
How to: Create Resource Files for ASP.NET Web Sites (Visual Studio)
Provides steps for creating .resx files that store text in different languages and for different cultures that can be displayed in
an ASP.NET Web page.
How to: Use Resources to Set Property Values in Web Server Controls
Provides steps for configuring controls to read property values from .resx files to dynamically display pages in different
languages.
How to: Retrieve Resource Values Programmatically
Provides steps for programmatically reading values from a language-specific and culture-specific .resx file.
Additional Globalization Techniques
How to: Localize Site-Map Data
Provides steps creating site maps that present information in different languages.
Bidirectional Support for ASP.NET Web Applications
Provides information on creating ASP.NET Web pages to be displayed in bidirectional languages.
How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization
Provides steps for configuring pages and Web sites to format dates, currency, and other culture-dependent values.
How to: Select an Encoding for ASP.NET Web Page Globalization
Provides steps for encoding page content and reading encoded browser information.
How to: Display Right-to-Left Text Using HTML Tags for Globalization
Provides steps for setting attributes in HTML elements to specify the direction in which text is displayed.
See Also
Concepts
How Do I in Visual Web Developer
Visual Web Developer

Security (How Do I in Visual Web Developer)


This page links to help on important information about securing your Web site. To view other categories of popular tasks
covered in Help, see How Do I in Visual Web Developer.
Walkthroughs
Walkthrough: Creating a Web Site with Membership and User Login (Visual Studio)
Provides a tutorial on adding Web site security using ASP.NET features to add a login page, authentication, and authorization.
Walkthrough: Managing Web Site Users with Roles
Provides a tutorial on assigning users to roles and securing resources based on roles.
Walkthrough: Encrypting Configuration Information Using Protected Configuration
Provides a tutorial on encrypting a portion of the Web.config file to protect sensitive information.
Security Guidelines
Securing Membership
Provides guidelines for improving the security of ASP.NET membership to create and manage users.
Securing Standard Controls
Provides guidelines for improving the security of form controls such as the AdRotator, TextBox, and ListBox controls.
Securing Roles
Provides guidelines for improving the security of using ASP.NET roles to manage authorization.
Securing ASP.NET Site Navigation
Provides guidelines for improving the security of site maps and navigation controls.
Securing Browser Definition Files
Provides guidelines for improving the security of the .browser files in which information about capabilities of individual
browsers is stored.
Securing Data Access
Provides guidelines for improving the security of data access in ASP.NET Web applications.
Securing Login Controls
Provides guidelines for improving the security of any Login, CreateUserWizard, PasswordRecovery, and other login
controls in your Web site.
Securing Profile Properties
Provides guidelines for improving the security of using ASP.NET profiles to create and manage user-specific information.
Securing Web Parts Pages
Provides guidelines for improving the security of ASP.NET Web pages that users can customize in their browser.
Securing Session State
Provides guidelines for improving the security of storing user-specific information in server memory.
Securing View State
Provides guidelines for improving the security of information stored by the ASP.NET page framework (and optionally by
you) in ASP.NET pages.
Securing ASP.NET Configuration
Provides guidelines for improving the security of .NET Framework configuration files.
Securing ASP.NET Health Monitoring
Provides guidelines for improving the security of raising Web events and handling them with built-in or custom providers.
General Security Practices
Basic Security Practices for Web Applications (Visual Studio)
Provides general information on security issues and security practices that apply to all Web sites.
Storing Sensitive Information Using ASP.NET
Provides guidelines for helping keep passwords and other sensitive information secure.
How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings
Provides steps for preventing malicious users from forcing unwanted code to run in your Web application.
How to: Display Safe Error Messages
Provides steps for configuring your Web application for proper error handling and for displaying error messages that do not
disclose sensitive information.
Configuring ASP.NET Process Identity
Provides information about configuring your Web application to run as a specific Windows user identity.
How to: Build and Run the Protected Configuration Provider Example
Provides steps for creating a custom encryption component for encrypting configuration elements.
Identifying Users
How to: Create an ASP.NET Login Page
Provides steps for creating an ASP.NET Web page that uses the Login control to authenticate users through ASP.NET
membership.
How to: Add a Login Button to an ASP.NET Web Page
Provides steps for adding a link to pages that helps users log in and out of your Web application.
How to: Use Advanced Features of the ASP.NET Login Control
Provides steps for changing the default appearance of the Login control.
How to: Use Advanced Features of the ASP.NET Login Control
Provides steps for customizing the behavior of the Login control.
How to: Enable User Registration
Provides steps for enabling users to register on your Web site using the CreateUserWizard control and ASP.NET
membership.
How to: Display the Name of the Current User
Provides steps for using the LoginName control to display the user's logged-in name (or a login link).
How to: Display Different Information to Anonymous and Logged In Users (Visual Studio)
Provides steps for using the LoginView control to create one display for logged-in users and a different one for users who
are not yet logged in.
How to: Enable User Password Recovery Using the ASP.NET PasswordRecovery Control
Provides steps for using the PasswordRecovery control to enable users to have a new or recovered password e-mailed to
them.
How to: Customize the PasswordRecovery Control
Provides steps for changing the default appearance of the PasswordRecovery control.
How to: Implement Simple Forms Authentication
Provides steps for creating a custom authentication system where you create your own login page and authentication logic.
How to: Sample Membership Provider Implementation
Provides steps for creating a custom provider to create and manage membership information.
How to: Sample Role-Provider Implementation
Provides steps for creating a custom provider to create and manage role information.
Data Security
Securing Data Access
Provides guidelines for improving the security of data access in ASP.NET Web applications.
How To: Secure Connection Strings when Using Data Source Controls (Visual Studio)
Provides steps for encrypting connection strings for database access.
How to: Access SQL Server as a Local User
Provides steps for configuring your application to log into Microsoft SQL Server on the same computer as the Web server.
How to: Access SQL Server Using a Mapped Windows Domain User
Provides steps for configuring your application to log into SQL Server using a specific Windows user account.
How to: Access SQL Server Using Predetermined Credentials
Provides steps for configuring your application to log into SQL Server using a user name and password that you build into
your application.
How to: Access SQL Server Using Windows Integrated Security
Provides steps for configuring your application to log into SQL Server with the user's current Windows user account
information.
See Also
Concepts
How Do I in Visual Web Developer
Visual Web Developer

Troubleshooting (How Do I in Visual Web Developer)


This page links to help on widely used tasks for finding errors that can occur in your Web applications. To view other
categories of popular tasks covered in Help, see How Do I in Visual Web Developer.
Walkthroughs
Walkthrough: Debugging Web Pages in Visual Web Developer
Provides a tutorial on using the integrated debugger in the Visual Web Developer designer to find errors in your code.
Walkthrough: Using Tracing in Visual Web Developer to Help Find Web Page Errors
Provides a tutorial on displaying detailed diagnostic information about individual page requests.
Walkthrough: Listening for WMI Events in ASP.NET Health Monitoring
Provides a tutorial on creating a custom health event provider that interacts with Windows Management Instrumentation
(WMI).
Error Handling
Error Handling in ASP.NET Pages and Applications
Provides information on catching errors and on how error information is made available in pages and applications.
How to: Handle Page-Level Errors
Provides steps for catching unhandled exceptions in an ASP.NET Web page.
How to: Handle Application-Level Errors
Provides steps for creating a global error handler to catch unhandled errors anywhere in an ASP.NET Web application.
Tracing
How to: Enable Tracing for an ASP.NET Page
Provides steps for displaying diagnostic information in an ASP.NET Web page.
How to: Enable Tracing for an ASP.NET Application
Provides steps for capturing diagnostic information for all ASP.NET pages in a Web site.
How to: View ASP.NET Trace Information with the Trace Viewer
Provides steps for displaying diagnostic information for the last 10 requests.
Writing Custom ASP.NET Trace Messages
Provides information on writing custom messages into the diagnostic tracing display.
Reading ASP.NET Trace Information
Provides information on interpreting the diagnostic information displayed in pages or in the trace viewer.
Debugging
Debugging Web Pages Overview
Provides information about debugging Web applications in Visual Web Developer.
Walkthrough: Debugging Web Pages in Visual Web Developer
Provides a tutorial on how to use the debugger with Web pages.
Health Monitoring
Walkthrough: Listening for WMI Events in ASP.NET Health Monitoring
Provides a tutorial on creating a custom health event provider that interacts with WMI.
Configuring ASP.NET Health Monitoring
Provides information on ASP.NET configuration settings required to add built-in or custom health monitoring events or
providers to your application.
How to: Send E-mail for Health Monitoring Notifications
Provides steps for configuring an ASP.NET application to send an e-mail notification when an ASP.NET health-monitoring
Web event occurs.
How to: Implement and Raise Custom ASP.NET Health Monitoring Events
Provides steps for creating a custom Web event.
How to: Implement the Health Monitoring Custom Provider Example
Provides steps for creating a health monitoring example.
See Also
Concepts
How Do I in Visual Web Developer
Visual Web Developer

Web Page Controls (How Do I in Visual Web Developer)


This page links to help on widely used tasks for working with ASP.NET Web server controls. To view other categories of
popular tasks covered in Help, see How Do I in Visual Web Developer.
The information in this topic is subdivided into the following sections:
Walkthroughs
Creating and Editing Controls
Programming Controls
Standard Controls
Data Controls
Login Controls
Navigation Controls
User Controls
Validation Controls
Web Parts Controls
Walkthroughs
Walkthrough: Displaying and Tracking Advertisements with the AdRotator Control
Provides a tutorial on using the AdRotator control to display randomly selected advertisements that you create.
Walkthrough: Creating a Web Site with Membership and User Login (Visual Studio)
Provides a tutorial on using login controls to add a login page, authentication, and authorization.
Walkthrough: Displaying a Menu on Web Pages
Provides a tutorial on using the Menu control.
Walkthrough: Controlling ASP.NET Menus Programmatically
Provides a tutorial on working with the Menu control in code.
Walkthrough: Adding Site Navigation to a Web Site
Provides a tutorial on using navigation controls to create ways for users to move between pages in your Web site.
Walkthrough: Creating Reusable Elements with ASP.NET User Controls
Provides a tutorial on using the Visual Web Developer designer to create a composite control that you can add to any
ASP.NET Web page.
Walkthrough: Validating User Input in a Web Forms Page
Provides a tutorial on using the validator controls to check user input.
Walkthrough: Creating a Web Parts Page in Visual Web Developer
Provides a tutorial on using Web Parts controls to create ASP.NET Web pages that users can customize in a browser.
Walkthrough: Creating a Basic ASP.NET Wizard Control
Provides a tutorial on using the Wizard control.
Walkthrough: Advanced Use of the ASP.NET Wizard Control
Provides a tutorial on programmatically controlling the Wizard control.
Walkthrough: Displaying an XML Document in a Web Forms Page Using Transformations
Provides a tutorial on using the Xml control to display the contents of an XML document on a page.
Walkthrough: Creating Web Pages for Mobile Devices
Provides a tutorial on creating an ASP.NET Web page that uses controls designed especially for mobile devices.
Walkthrough: Creating an Accessible Web Application
Provides a tutorial on configuring Web server controls to create an ASP.NET Web page that can be accessed by people with
disabilities, including how to test accessibility.
Data (How Do I in Visual Web Developer)
Provides links to topics that describe how to use data controls to display and edit data on an ASP.NET Web page.
Creating and Editing Controls
How to: Add Web Server Controls to a Web Forms Page Using the Web Forms Designer
Provides steps for how to use designer features to create and edit Web server controls.
How to: Add Server Controls to an ASP.NET Web Page Using ASP.NET Syntax
Provides steps for adding controls to a page by editing the markup directly.
How to: Add HTML Server Controls to an ASP.NET Web Page Using the Designer
Provides steps for creating programmable HTML elements in the Visual Web Developer designer.
How to: Add HTML Server Controls to a Web Page Using ASP.NET Syntax
Provides steps for creating programmable HTML elements by editing the markup directly.
How to: Convert HTML Server Controls to HTML Elements (Visual Studio)
Provides steps for treating HTML elements as Web server controls.
How to: Specify Whether ASP.NET Web Server Controls Post to the Server
Provides steps for how to configure a control to cause the page to post back immediately when users select a value.
How to: Set ASP.NET Server Control Properties (Visual Studio)
Provides steps for how to use the Visual Web Developer designer to set control properties.
How to: Set Web Server Control Properties Based on Simple Values or Enumerations
Provides steps for how to set properties with text or integer values, or to one of a set of predefined values.
How to: Set Web Server Control Properties in Collections
Provides steps for how to set properties that contain multiple individual elements.
How to: Set Web Server Control Unit Properties
Provides steps for how to set sizes (such as height or width).
How to: Set Web Server Control Color Properties
Provides steps for how to set foreground and background colors.
How to: Set HTML Attributes for Controls in ASP.NET Web Pages
Provides steps for how to add HTML (or other markup) attributes to Web server controls, both declaratively and
programmatically.
How to: Set ASP.NET Server Control Style Properties Using ASP.NET Syntax
Provides steps for setting control properties by editing the markup directly.
How to: Set ASP.NET Server Control Style Properties in the Designer
Provides steps for using the Visual Web Developer designer to set individual style properties.
How to: Use Resources to Set Property Values in Web Server Controls (Visual Studio)
Provides steps for how to configure controls to read property values from resource (.resx) files to dynamically display pages
in different languages.
How to: Set Access Keys for ASP.NET Web Server Controls
Provides steps for how to configure controls so that users can jump to them using ALT-key combinations.
Programming Controls
How to: Create Event Handlers in ASP.NET Web Pages (Visual Studio)
Provides steps for writing code that responds to events in the page and in controls, using the Visual Web Developer
designer.
How to: Connect Multiple Events to a Single Event Handler in ASP.NET Web Pages
Provides steps for writing code that can respond to events from different controls, using the Visual Web Developer designer.
How to: Determine which Web Server Control Raised an Event
Provides steps for using event information to determine the source of an event.
How to: Read HTML Attributes for Controls in Web Forms Pages
Provides steps for reading attributes from control markup that are not exposed as properties.
How to: Set Focus on ASP.NET Web Server Controls
Provides steps for setting the focus on a control when the page runs.
How to: Respond to Button Web Server Control Events in Client Script
Provides steps for adding a client-script event handler to an ASP.NET Web server button control.
How to: Set ASP.NET Server Control Style Properties Programmatically
Provides steps for using code to work with style properties of a control.
How to: Set HTML Server Control Properties Programmatically
Provides steps for using code to set attributes of HTML elements.
How to: Add Controls to an ASP.NET Web Page Programmatically
Provides steps for using code to create control instances and add them to the page.
How to: Locate the Web Forms Controls on a Page by Walking the Controls Collection
Provides steps for using code to find a specific control on a page.
How to: Access Members of a Web Server Control's Naming Container
Provides steps for using code to find a specific control on a page.
How to: Locate Child Controls by ID in an ASP.NET Web Page
Provides steps for using code to find a specific control on a page.
Standard Controls
How to: Display Ads From an XML File Using the AdRotator Web Server Control
Provides steps for displaying advertisement information from an XML file in the AdRotator control.
How to: Display Ads From a Database Using the AdRotator Web Server Control
Provides steps for displaying advertisement information from a database in the AdRotator control.
How to: Select Ads in an AdRotator Web Server Control Programmatically
Provides steps for displaying specific ads in the AdRotator control.
How to: Add BulletedList Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a BulletedList control using the Visual Web Developer designer.
How to: Respond to User Clicks in BulletedList Web Server Controls (Visual Studio)
Provides steps for running code when users select an item in a BulletedList control.
How to: Add Button Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating Button, LinkButton, and ImageButton controls using the Visual Web Developer designer.
How to: Respond to Button Web Server Control Events
Provides steps for running code when users click a Button, LinkButton, or ImageButton control.
How to: Determine Coordinates in an ImageButton Web Server Control
Provides steps for reading the x and y coordinates of where a user clicked in an ImageButton control.
How to: Customize Calendar Web Server Control Appearance
Provides steps for changing the default look of the Calendar control.
How to: Customize Individual Days in a Calendar Web Server Control
Provides steps for changing the default look of days in the Calendar control.
How to: Format Calendar Web Server Control Elements Using Styles
Provides steps for setting the look of days, weeks, months, weekends and other elements in a Calendar control.
How to: Control User Date Selection in a Calendar Web Server Control
Provides steps for enabling users to select single dates, weeks, or months in a Calendar control.
How to: Control Month Navigation in a Calendar Web Server Control
Provides steps for enabling users to navigate from month to month using a Calendar control.
How to: Respond to Date Selection in a Calendar Web Server Control
Provides steps for running code when users select a date in the Calendar control.
How to: Read Selected Dates in the Calendar Web Server Control
Provides steps for reading the user's selection in a Calendar control.
How to: Set Today's Date Programmatically in a Calendar Web Server Control
Provides steps for setting the current date in a Calendar control.
How to: Select Dates Programmatically in a Calendar Web Server Control
Provides steps for making a date selection in code in a Calendar control.
How to: Display Selected Dates from a Database in the Calendar Control
Provides steps for reading dates from a database and displaying them in a Calendar control.
How to: Add CheckBox Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a CheckBox control using the Visual Web Developer designer.
How to: Get and Set a CheckBox Web Server Control Value Programmatically
Provides steps for reading and writing the selection in a CheckBox control.
How to: Add CheckBoxList Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a CheckBoxList control using the Visual Web Developer designer. You can use this control to
display true/false choices from a database or other source.
How to: Set Layout in a CheckBoxList Web Server Control
Provides steps for specifying whether a CheckBoxList control is displayed in rows or columns.
How to: Respond to User Selection in a CheckBox Web Server Control
Provides steps for running code when users select an item in a CheckBoxList control.
How to: Set Layout in a RadioButtonList Web Server Control
Provides steps for specifying whether a CheckBoxList control is displayed in rows or columns.
How to: Add DropDownList Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a DropDownList control using the Visual Web Developer designer.
How to: Upload Files with the FileUpload Web Server Control
Provides steps for creating a FileUpload control using the Visual Web Developer designer. This control enables users to
send files to the server from their computer.
How to: Add HyperLink Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a Hyperlink control using the Visual Web Developer designer.
How to: Add Image Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating an Image control using the Visual Web Developer designer.
How to: Add ImageButton Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating an ImageButton control using the Visual Web Developer designer.
How to: Add ImageMap Web Server Controls to a Web Page (Visual Studio)
Provides steps for creating an ImageMap control using the Visual Web Developer designer.
How to: Respond to User Clicks in ImageMap Web Server Controls
Provides steps for running code when users click a hot spot in an ImageMap control.
How to: Add Label Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a Label control using the Visual Web Developer designer.
How to: Use Label Web Server Controls as Captions
Provides steps for associating a Label control with another control and using it as a caption with an optional shortcut key.
How to: Add ListBox Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a ListBox control using the Visual Web Developer designer.
How to: Add Literal Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a Literal control using the Visual Web Developer designer. This is a way to add static text to the
page in code.
How to: Add MultiView Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating MultiView and View controls using the Visual Web Developer designer.
How to: Add Panel Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a Panel control using the Visual Web Developer designer. You can use this control as the
container for other controls.
How to: Add PlaceHolder Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a Placeholder control using the Visual Web Developer designer. You can use this control as the
container for other controls.
How to: Add RadioButton Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a RadioButton control using the Visual Web Developer designer.
How to: Respond to a User Selection in a RadioButton Web Server Control Group
Provides steps for running code when users click a RadioButton control.
How to: Set and Get the Selection in a RadioButton Web Server Control
Provides steps for reading and writing the selection in a RadioButton control, whether singly or in a group.
How to: Add RadioButtonList Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a RadioButtonList control using the Visual Web Developer designer. You can use this control to
display mutually exclusive choices from a database or other source.
How to: Add Table Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a Table control, which enables you to manage tables on the page in code.
How to: Add Rows and Cells Dynamically to a Table Web Server Control
Provides steps for using code to create rows and cells in a Table control.
How to: Set a TextBox Web Server Control for Password Entry
Provides steps for configuring a TextBox control to display text as stars or dots.
How to: Specify Multiline Input for a TextBox Web Server Control
Provides steps for configuring a TextBox control to enable users to enter more than one line of text.
How to: Get and Set Values in TextBox Web Server Controls
Provides steps for reading and writing the value in a TextBox control.
How to: Respond to Changes in a TextBox Web Server Control
Provides steps for running code when users change text in a TextBox control.
How to: Add XML Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating an Xml control using the Visual Web Developer designer. This control enables you to display an
XML document on the page.
How to: Load XML Data in the XML Web Server Control
Provides steps for configuring an Xml control to display an XML document or XML stream.
How to: Transform XML Data in the XML Web Server Control
Provides steps for using a transformation with the Xml control to customize the display of XML data.
How to: Add Items in List Web Server Controls (Visual Studio)
Provides steps for adding elements to a BulletedList, CheckBoxList, DropDownList, ListBox, or RadioButtonList control
using the Visual Web Developer designer.
How to: Set the Selection in List Web Server Controls (Visual Studio)
Provides steps for specifying the current item in a CheckBoxList, DropDownList, ListBox, or RadioButtonList control.
How to: Determine the Selection in List Web Server Controls
Provides steps for using code to read the current element in a CheckBoxList, DropDownList, ListBox, or RadioButtonList
control.
How to: Respond to Changes in List Web Server Controls
Provides steps for running code when users select an item in a CheckBoxList, DropDownList, ListBox, or RadioButtonList
control.
How to: Populate List Web Server Controls from a Data Source (Visual Studio)
Provides steps for binding the BulletedList, CheckBoxList, DropDownList, ListBox, or RadioButtonList control to data in
a database.
Data Controls
How to: Add DataList Web Server Controls to an ASP.NET Web Page (Visual Studio)
Provides steps for creating a DataList control, which enables you to display data in an HTML table using a layout you define.
Walkthrough: Displaying and Formatting Data with the DataList Web Server Control
Provides a tutorial on creating a DataList control, which enables you to display data in an HTML table using a layout you
define.
How to: Allow Users to Delete Items in DataList Web Server Controls
Provides steps on configuring the DataList control to enable users to delete data records.
How to: Allow Users to Edit Items in DataList Web Server Controls
Provides steps on configuring the DataList control to enable users to edit data records.
How to: Allow Users to Select Items in DataList Web Server Controls
Provides steps on configuring the DataList control to enable users to select (highlight) a specific item.
How to: Customize Items Dynamically in the DataList Web Server Control
Provides steps for how to use code to change the look or behavior of items in a DataList control at run time.
How to: Specify Flow or Table Format in DataList Web Server Controls
Provides steps for how to set the layout of a DataList control.
How to: Specify Horizontal or Vertical Layout in DataList Web Server Controls
Provides steps for how to set the layout of a DataList control.
Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control
Provides a tutorial on using a DetailsView control to enable users to edit existing records and create new ones.
Modifying Data Using a DetailsView Web Server Control
Provides information on using the DetailsView control to enable users to edit data one record at a time.
Paging in a DetailsView Web Server Control
Provides information on configuring the DetailsView control to enable users to page through multiple records, one at a
time.
Walkthrough: Displaying Formatted Data in Web Pages with the FormView Web Server Control
Provides a tutorial on using a FormView control to display a single record at a time, using free-form layout templates that
you define.
Modifying Data Using a FormView Web Server Control
Provides steps on using a FormView control to enable users to edit data one record at a time.
Paging in a FormView Web Server Control
Provides information on configuring the FormView control to enable users to page through multiple records, one at a time.
Walkthrough: Basic Data Access in Web Pages
Provides a tutorial on how to use the GridView control and SqlDataSource controls to display data on an ASP.NET Web
page.
Walkthrough: Creating a Web Page to Display Access Database Data
Provides a tutorial on how to use the GridView control and AccessDataSource controls to display data from a Microsoft
Access database on an ASP.NET Web page.
Walkthrough: Creating Master/Detail Web Pages in Visual Studio
Provides a tutorial on how to use the DropDownList, GridView, DetailsView, and SqlDataSource controls to create pages
that display lists of data where the user can select an individual record to examine further.
Walkthrough: Simple Sorting for the GridView Web Server Control
Provides a tutorial on how to use built-in features of the GridView control to enable users to sort the displayed data.
How to: Customize Controls for Editing in the GridView Web Server Control
Provides steps on configuring the GridView control to display the controls that you choose when in edit mode.
How to: Set GridView Web Server Control Column Width Dynamically
Provides steps for how to set column widths in the GridView according to the width of the data being displayed.
How to: Respond to Button Events in Data-Bound Controls
Provides steps for how to handle events raised by button controls in list data controls such as the GridView, DataList, and
Repeater controls.
How to: Enable Default Deleting in the GridView Web Server Control
Provides steps on configuring the GridView control to enable users to delete data records.
How to: Enable Default Editing in the GridView Web Server Control
Provides steps on configuring the GridView control to enable users to edit data records.
How to: Enable Default Paging in the GridView Web Server Control
Provides steps on configuring the GridView control to enable users to page through long lists of data records.
Walkthrough: Data Binding to a Custom Business Object
Provides a tutorial on how to use the ObjectDataSource control to create multi-tier data access in an ASP.NET Web
application.
Walkthrough: Data Binding Web Pages with a Visual Studio Data Component
Provides a tutorial on how to use Visual Studio tools to create a data-access object that you can use with the
ObjectDataSource control.
How to: Add Repeater Web Server Controls to a Web Forms Page (Visual Studio)
Provides steps for creating a Repeater control, which enables you to display data on an ASP.NET Web page using free-form
layout templates that you define.
How to: Enable Filtering for SqlDataSource Controls (Visual Studio)
Provides steps for how to configure a SqlDataSource control to enable the results of a query to be further refined with
filtering.
How to: Respond to Button Events in DataList, Repeater, or GridView Items
Provides steps for how to handle events raised by button controls in list data controls such as the GridView, DataList, and
Repeater controls.
Walkthrough: Displaying Hierarchical Data in a TreeView Control
Provides a tutorial on using the TreeView control to display XML data.
How to: Create ASP.NET Web Control Templates Declaratively
Provides steps for creating templates in the GridView, DetailsView, FormView, DataList, and Repeater controls by editing
the markup directly.
How to: Bind to Data in a Templated Control
Provides steps on adding data-bound controls to templates in controls such as the GridView, DetailsView, FormView,
DataList, and Repeater controls.
How To: Create ASP.NET Web Server Control Templates Dynamically
Provides steps for creating templates in the GridView, DetailsView, FormView, DataList, and Repeater controls in code.
Login Controls
Walkthrough: Creating a Web Site with Membership and User Login (Visual Studio)
Provides a tutorial on using login controls to add a login page, authentication, and authorization.
How to: Add a Login Button to an ASP.NET Web Page
Provides steps for adding a link to pages that helps users log in and out of your Web application.
How to: Use Advanced Features of the ASP.NET Login Control
Provides steps for changing the default appearance of the Login control.
How to: Customize the PasswordRecovery Control
Provides steps for changing the default appearance of the PasswordRecovery control.
How to: Create an ASP.NET Login Page
Provides steps for creating an ASP.NET Web page that uses the Login control to authenticate users through ASP.NET
membership.
How to: Enable User Registration
Provides steps for enabling users to register on your Web site using the CreateUserWizard control and ASP.NET
membership.
How to: Enable User Password Recovery Using the ASP.NET PasswordRecovery Control
Provides steps for using the PasswordRecovery control to enable users to have a new or recovered password e-mailed to
them.
How to: Use Advanced Features of the ASP.NET Login Control
Provides steps for customizing the behavior of the Login control.
How to: Display the Name of the Current User
Provides steps for using the LoginName control to display the user's logged-in name (or a login link).
How to: Display Different Information to Anonymous and Logged In Users (Visual Studio)
Provides steps for using the LoginView control to create one display for logged-in users and a different one for users who
are not yet logged in.
Navigation Controls
How to: Display Site-Map Data in Non-Hierarchical Web Server Controls
Provides steps for using a control such as a DropDownList control to work with site map data.
Walkthrough: Controlling ASP.NET Menus Programmatically
Provides a tutorial on how to work with the Menu control in code.
How to: Customize the Appearance of SiteMapPath Web Server Controls
Provides steps for changing the default appearance of the SiteMapPath control.
How to: Filter the Nodes Retrieved by SiteMapDataSource Web Server Controls
Provides steps for programmatically determining what site map information to display to users.
How to: Add or Delete TreeView Node Elements (Visual Studio)
Provides steps for populating a TreeView control with static nodes.
How to: Customize the ASP.NET CreateUserWizard Control
Provides steps for changing the default appearance of a Wizard control.
User Controls
How to: Create ASP.NET User Controls (Visual Studio)
Provides steps on using the Visual Web Developer designer to create a composite control that you can add to any ASP.NET
Web page.
How to: Convert Web Forms Pages into ASP.NET User Controls
Provides steps on configuring an existing ASP.NET Web page to be a user control.
How to: Include ASP.NET User Controls in Web Pages (Visual Studio)
Provides steps on adding a user control to an ASP.NET Web page in the Visual Web Developer designer.
How to: Create Instances of ASP.NET User Controls Programmatically
Provides steps on programmatically creating user controls and adding them to an ASP.NET Web page.
Validation Controls
How to: Validate Required Entries for ASP.NET Server Controls
Provides steps for preventing users from skipping a field in a page.
How to: Validate Against a Specific Value for ASP.NET Server Controls
Provides steps for requiring users to enter one of a specific set of values.
How to: Validate Against a Data Type for ASP.NET Server Controls
Provides steps for requiring users to enter a value that is an integer, date, or other type.
How to: Validate Against Patterns for ASP.NET Server Controls
Provides steps for requiring users to enter a value that matches a certain pattern, such as a phone number or e-mail address.
How to: Validate Against a Range of Values for ASP.NET Server Controls
Provides steps for requiring users to enter a value that is between a minimum and maximum value (numbers or text).
How to: Validate Against Values in a Database for ASP.NET Server Controls
Provides steps for using custom logic to look up values in a database to check a user's entry.
How to: Disable Validation for ASP.NET Server Controls
Provides steps for conditionally turning off validation.
How to: Validate with a Custom Function for ASP.NET Server Controls
Provides steps for creating your own logic for validating user entries.
How to: Test Validity Programmatically for ASP.NET Server Controls
Provides steps for determining in code whether validation checks have passed or failed.
How to: Validate Programmatically for ASP.NET Server Controls
Provides steps for using code to trigger the check for one or more validation controls.
How to: Display Server Side Custom Validation Messages for ASP.NET Server Controls
Provides steps for changing the appearance and text for validation errors.
How to: Control Validation Error Message Display for ASP.NET Server Controls
Provides steps for configuring validation controls to specify how and where error messages appear.
How to: Format Validation Error Messages for ASP.NET Server Controls
Provides steps for using HTML and properties to customize the look of validation error messages.
How to: Specify Layout for In-Place Messages On ASP.NET Server Controls
Provides steps for specifying whether validation controls take up space on the page when not displaying an error message.
Web Parts Controls
Web Parts Control Set Overview
Provides information on different pieces you can use to create customizable ASP.NET Web pages.
Walkthrough: Creating a Web Parts Page in Visual Web Developer
Provides a tutorial on using Web Parts controls to create ASP.NET Web pages that users can customize in a browser.
Web Parts Personalization Overview
Provides information on tracking customizations for individual users.
Walkthrough: Implementing Web Parts Personalization with a User Control
Provides a tutorial on how to create an ASP.NET user control (rather than a custom control) to track user-specific
information.
Walkthrough: Changing Display Modes on a Web Parts Page
Provides a tutorial on how to create a page where users can switch between display and edit modes to customize the page.
How to: Treat a User Control as a Web Parts Control
Provides steps for how to create an ASP.NET user control (rather than a custom control) to track user-specific information.
How to: Declare a Static Connection between Two Web Parts Controls
Provides steps for creating a static link between Web Parts controls declaratively.
How to: Enable Shared Personalization of Web Parts Pages
Provides steps for configuring Web Parts personalization so that user information is available to other users.
See Also
Concepts
How Do I in Visual Web Developer
Visual Web Developer

Web Pages (How Do I in Visual Web Developer)


This page links to help on widely used tasks for creating and programming ASP.NET Web pages using Visual Web Developer.
To view other categories of popular tasks covered in Help, see How Do I in Visual Web Developer.
Walkthroughs
Walkthrough: Creating a Basic Web Page in Visual Web Developer
Provides a tutorial on creating and editing an ASP.NET Web page in Visual Web Developer, including an overview of the Web
development environment.
Walkthrough: Creating a Basic Web Page with Code Separation in Visual Web Developer
Provides a tutorial on how to work with ASP.NET code-behind pages in the Visual Web Developer designer.
Walkthrough: Basic HTML Editing in Visual Web Developer
Provides a tutorial on working with markup (HTML) in the Visual Web Developer designer.
Walkthrough: Advanced HTML Editing in Visual Web Developer
Provides a tutorial on additional HTML editing features in the Visual Web Developer designer.
Walkthrough: Editing HTML Tables in Visual Web Developer
Provides a tutorial on adding and editing HTML tables in the Visual Web Developer designer.
Walkthrough: Working with Cascading Style Sheet Styles in Visual Web Developer
Provides a tutorial on features in the Visual Web Developer designer that help you create styles and cascading style sheets.
Walkthrough: Code Editing in Web Pages in Visual Web Developer
Provides a tutorial on features of the code editor in the Visual Web Developer designer that help you create code quickly and
accurately.
Walkthrough: Debugging Web Pages in Visual Web Developer
Provides a tutorial on using the integrated debugger in the Visual Web Developer designer to find errors in your code.
Walkthrough: Displaying a Menu on Web Pages
Provides a tutorial on creating Web page menus.
Walkthrough: Customizing a Web Site Using Themes in Visual Studio
Provides a tutorial on creating a consistent look for pages in your Web site.
Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer
Provides a tutorial on creating a consistent layout for pages in your Web site.
Walkthrough: Creating a Web Parts Page in Visual Web Developer
Provides a tutorial on creating ASP.NET Web pages that users can customize in a browser.
Walkthrough: Using Shared Code in Web Sites in Visual Web Developer
Provides a tutorial on creating and using components in an ASP.NET Web site without having to compile them.
Walkthrough: Creating Web Pages for Mobile Devices
Provides a tutorial on creating an ASP.NET Web page that uses controls designed especially for mobile devices.
Walkthrough: Validating User Input in a Web Forms Page
Provides a tutorial on checking user input in an ASP.NET Web page.
Walkthrough: Using Resources for Localization with ASP.NET
Provides a tutorial on creating Web pages that can display information in different languages.
Walkthrough: Creating an Accessible Web Application
Provides a tutorial on creating an ASP.NET Web page that can be accessed by people with disabilities, including how to test
accessibility.
Walkthrough: Using Output Caching to Enhance Web Site Performance
Provides a tutorial on storing pages in memory for faster performance.
Walkthrough: Using ASP.NET Output Caching with SQL Server
Provides a tutorial on caching pages that are removed from the cache only when their dependent data in SQL Server
changes.
Creating and Editing Web Pages
How to: Add ASP.NET Web Pages to a Web Site (Visual Studio)
Provides steps for creating ASP.NET Web pages using Visual Web Developer.
How to: Test Web Pages in Visual Web Developer
Provides steps for testing Web pages while working in the Visual Web Developer designer.
How to: Add Cascading Style Sheet Attributes in Design View
Provides steps for editing styles and cascading style sheets in the Visual Web Developer designer.
How to: Link Cascading Style Sheets to ASP.NET Web Pages (Visual Studio)
Provides steps for adding a cascading style sheet link to an ASP.NET Web page in the Visual Web Developer designer.
How to: Precompile ASP.NET Web Sites
Provides steps for compiling an entire Web site to check pages for errors or for deployment to a production server.
How to: Redirect Users to Another Page
Provides steps for programmatically navigating to another Web page.
Layout and Appearance
ASP.NET Master Pages Overview
Provides information on using master pages to create a consistent layout in your Web site.
How to: Create Content Pages for an ASP.NET Master Page (Visual Studio)
Provides steps for how to create content to merge with a master page using the Visual Web Developer designer.
How to: Reference ASP.NET Master Page Content
Provides steps for how to programmatically read information from a master page.
How to: Add Cascading Style Sheet Attributes in Design View
Provides steps for how to create style rules for individual elements in a Web page using the Visual Web Developer designer.
How to: Create External Cascading Style Sheets (Visual Studio)
Provides steps for creating a new cascading style sheet and adding rules to it, and steps for how to configure the Visual Web
Developer designer to validate against a specific CSS schema.
How to: Define ASP.NET Page Themes (Visual Studio)
Provides steps for how to create a collection of control properties and styles that you can apply as a unit to pages or Web
sites.
How to: Apply ASP.NET Themes
Provides steps for how to apply an existing theme to pages or to a Web site.
How to: Apply ASP.NET Themes Programmatically
Provides steps for how to apply a theme in code.
How to: Disable ASP.NET Themes
Provides steps for how to prevent a theme from being applied to an individual page or to a Web site.
Programming ASP.NET Web Pages
How to: Create Event Handlers in ASP.NET Web Pages (Visual Studio)
Provides steps for how to write code that responds to events in the page and in controls, using the Visual Web Developer
designer.
How to: Connect Multiple Events to a Single Event Handler in ASP.NET Web Pages
Provides steps for how to write code that can respond to events from different controls, using the Visual Web Developer
designer.
How to: Post ASP.NET Web Pages to a Different Page
Provides steps for how to create linked pages by posting one page to another.
How to: Detect Browser Types in ASP.NET Web Pages
Provides steps for how to read browser information to determine browser capabilities programmatically in an ASP.NET Web
page.
How to: Call a Web Service
Provides steps for how to programmatically invoke methods in an XML Web service.
Web Parts
ASP.NET Web Parts Overview
Provides information on Web Parts, which enable you to create pages that users can customize in their browsers.
Web Parts Control Set Overview
Provides information on different pieces you can use to create customizable ASP.NET Web pages.
Walkthrough: Creating a Web Parts Page in Visual Web Developer
Provides a tutorial on using Web Parts controls to create ASP.NET Web pages that users can customize in a browser.
Web Parts Personalization Overview
Provides information on tracking customizations for individual users.
Walkthrough: Implementing Web Parts Personalization with a User Control
Provides a tutorial on how to create an ASP.NET user control (rather than a custom control) to track user-specific
information.
Walkthrough: Changing Display Modes on a Web Parts Page
Provides a tutorial on how to create a page where users can switch between display and edit modes to customize the page.
How to: Treat a User Control as a Web Parts Control
Provides steps for how to create an ASP.NET user control (rather than a custom control) to track user-specific information.
How to: Declare a Static Connection between Two Web Parts Controls
Provides steps for creating a static link between Web Parts controls declaratively.
How to: Enable Shared Personalization of Web Parts Pages
Provides steps for configuring Web Parts personalization so that user information is available to other users.
State Management
How to: Write a Cookie
Provides steps for creating a cookie, which stores small amounts of data on the user's browser.
How to: Read a Cookie
Provides steps for programmatically reading a cookie stored earlier.
How to: Delete a Cookie
Provides steps for removing cookies from a user's computer.
How to: Pass Values Between ASP.NET Web Pages
Provides steps for storing values in one page that can be accessed in another page.
How to: Save Values in Application State
Provides steps for storing information in a global storage area that is available to all pages and components in a Web site.
How to: Read Values from Application State
Provides steps for reading global values.
How to: Save Values in Session State
Provides steps for storing user-specific information that is available as long as a user is working with pages in your Web site.
How to: Read Values from Session State
Provides steps for reading user-specific information that is available as long as a user is working with pages in your Web
site.
How to: Save Values in View State
Provides steps for storing information in a Web page while users are working with that page.
How to: Read Values from View State
Provides steps for reading information stored earlier in a page.
Client Script
How to: Add Client Script Events to ASP.NET Web Server Controls
Provides steps for writing client script in ASP.NET Web pages that responds to user actions such as mouse clicks.
How to: Create Scripts and Edit Event Handlers
Provides steps for writing client script while working in Source view of the Visual Web Developer designer.
How to: Respond to Button Web Server Control Events in Client Script
Provides steps for adding client-script event handling to ASP.NET button controls, even if the buttons also have server-side
event handlers.
How to: Add Client Script Dynamically to ASP.NET Web Pages
Provides steps for programmatically calling ASP.NET methods that inject client script into a page.
Performance
How to: Set the Cacheability of an ASP.NET Page Declaratively
Provides steps for setting a page's cache policy in markup.
How to: Set a Page's Cacheability Programmatically
Provides steps for setting a page's cache policy in code.
How to: Set Expiration Values for ASP.NET Page Caching
Provides steps for specifying when a page should be removed from the cache.
How to: Check the Validity of a Cached Page
Provides steps for determining whether a cached page has been invalidated.
How to: Cache Page Output with File Dependencies
Provides steps for caching different versions of a page based on changes to a file.
How to: Cache Page Output with Cache Key Dependencies
Provides steps for caching different versions of a page based on other information in the cache.
How to: Cache Versions of a Page Using Requesting Browser
Provides steps for caching different versions of a page based on information about the user's browser type.
How to: Cache Versions of a Page Using Parameters
Provides steps for caching different versions of a page based on information sent from the browser, such as query string or
post values.
How to: Cache Versions of a Page Using HTTP Headers
Provides steps for caching different versions of a page based on information sent in the browser headers, such as the
Accept-Language value.
How to: Cache Versions of a Page Using Custom Strings
Provides steps for caching different versions of a page based on a criterion that you create.
How to: Cache Multiple Versions of a User Control Based on Parameters
Provides steps for caching a portion of a page as a user control.
How to: Cache Multiple Versions of a User Control by Using Declarative Attributes
Provides steps for caching different portions of a page separately using the same user control.
Dynamically Updating Portions of a Cached Page
Provides information on caching some parts of a page while being able to update other parts of the page.
How to: Add Items to the Cache
Provides steps for storing information in the ASP.NET cache for quick retrieval.
How to: Retrieve Values of Cached Items
Provides steps for reading information stored previously in the cache.
How to: Delete Items from the Cache in ASP.NET
Provides steps for removing information you previously put in the cache.
How to: Notify an Application When an Item Is Removed from the Cache
Provides steps for raising an event when information is removed from the cache.
Caching in ASP.NET with the SqlCacheDependency Class
Provides information on caching pages that are removed from the cache only when their dependent data in SQL Server
changes.
Localization
How to: Create Resource Files for ASP.NET Web Sites
Provides steps for how to create resource (.resx) files that store text in different languages and for different cultures that can
be displayed in an ASP.NET Web page.
How to: Use Resources to Set Property Values in Web Server Controls (Visual Studio)
Provides steps for how to configure controls to read property values from .resx files to dynamically display pages in different
languages.
How to: Localize Site-Map Data
Provides steps for how to create site maps that present information in different languages.
How to: Retrieve Resource Values Programmatically
Provides steps for programmatically reading values from a language-specific and culture-specific .resx file.
Accessibility
Accessibility Support in ASP.NET
Provides information on features of ASP.NET that help you create Web sites that conform to accessibility standards.
How to: Check Accessibility of Web Pages in Visual Web Developer
Provides steps for validating in the Visual Web Developer designer that an ASP.NET Web page meets accessibility guidelines.
(This feature is not available in Visual Web Developer Express Edition.)
Devices and Browsers
Walkthrough: Creating Web Pages for Mobile Devices
Provides a tutorial on creating an ASP.NET Web page that uses controls designed especially for mobile devices.
See Also
Concepts
How Do I in Visual Web Developer
Visual Web Developer

Web Sites (How Do I in Visual Web Developer)


This page links to help on widely used information pertaining to creating and managing ASP.NET Web sites. To view other
categories of popular tasks covered in Help, see How Do I in Visual Web Developer.
Walkthroughs
Walkthrough: Creating a Basic Web Page in Visual Web Developer
Provides a tutorial on creating and editing an ASP.NET Web page in Visual Web Developer, including an overview of the Web
development environment.
Walkthrough: Creating a Basic Web Page with Code Separation in Visual Web Developer
Provides a tutorial on working with ASP.NET code-behind pages in the Visual Web Developer designer.
Walkthrough: Creating a Local IIS Web Site in Visual Web Developer
Provides a tutorial on creating a Web site under the IIS Web root on your own computer.
Walkthrough: Editing Web Sites with FTP in Visual Web Developer
Provides a tutorial on creating a Web site in a local folder on your computer and testing it using the ASP.NET Development
Server.
Walkthrough: Adding Site Navigation to a Web Site
Provides a tutorial on using site maps and creating navigation using a menu, a tree view, and a site map path control
(sometimes referred to as a breadcrumb).
Walkthrough: Creating a Web Site with Membership and User Login (Visual Studio)
Provides a tutorial on adding Web site security using ASP.NET features to add a login page, authentication, and authorization.
Walkthrough: Copying a Web Site Using the Copy Web Site Tool
Provides a tutorial on synchronizing local and remote versions of a Web site.
Walkthrough: Publishing a Web Site
Provides a tutorial on deploying your Web site to a production server.
Walkthrough: Displaying a Menu on Web Pages
Provides a tutorial on adding an application menu to pages on your site.
Walkthrough: Maintaining Web Site User Information with Profile Properties
Provides a tutorial on using ASP.NET profiles to gather information from users and store it for use each time they visit.
Walkthrough: Customizing a Web Site Using Themes in Visual Studio
Provides a tutorial on creating a consistent look for pages in your Web site.
Walkthrough: Creating and Using ASP.NET Master Pages in Visual Web Developer
Provides a tutorial on creating a consistent layout for pages in your Web site.
Walkthrough: Using Shared Code in Web Sites in Visual Web Developer
Provides a tutorial on creating and using components in an ASP.NET Web site without having to compile them.
Walkthrough: Creating and Using an ASP.NET Web Service in Visual Web Developer
Provides a tutorial on creating an XML Web service in Visual Web Developer, and a Web site that connects to the Web
service and calls its methods.
Walkthrough: Using Resources for Localization with ASP.NET
Provides a tutorial on creating Web pages that can display information in different languages.
Walkthrough: Creating an Accessible Web Application
Provides a tutorial on creating an ASP.NET Web page that can be accessed by people with disabilities, including how to test
accessibility.
Walkthrough: Using Output Caching to Enhance Web Site Performance
Provides a tutorial on storing pages in memory for faster performance.
Creating and Editing
Types of Web Sites in Visual Web Developer
Provides an overview of where you can create and edit the files for your Web sites, and what Web server or other software
you need in each case.
How to: Create File System Web Sites
Provides steps for how to create a Web site on your local computer even if you are not running Internet Information Services
(IIS).
How to: Create Local IIS Web Sites
Provides steps for how to create a Web site under the IIS Web root on your own computer.
How to: Create Remote IIS Web Sites
Provides steps for how to create a Web site under the IIS Web root on a remote computer.
How to: Create IIS Virtual Directories in Visual Web Developer
Provides steps for how to create a Web site using IIS in which files are stored in an arbitrary folder, not under the IIS Web site
root.
How to: Open Web Sites Using FTP
Provides steps for how to connect to and open a Web site on an FTP server.
How to: Add ASP.NET Web Pages to a Web Site (Visual Studio)
Provides steps for how to work with individual files in a Web site.
Navigation
ASP.NET Site Navigation Overview
Provides information on ASP.NET site maps (files that describe the site layout) and on ASP.NET controls that are designed for
adding navigation to Web pages.
How to: Add Simple Site Navigation
Provides steps for how to use a site map and navigation controls.
How to: Localize Site-Map Data
Provides steps for how to create site maps that present information in different languages.
How to: Customize the Appearance of SiteMapPath Web Server Controls
Provides steps for how to set the look and behavior of SiteMapPath controls (sometimes known as breadcrumbs).
How to: Display Site-Map Data in Non-Hierarchical Web Server Controls
Provides steps for how to use site maps with controls that do not inherently support hierarchies.
How to: Filter the Nodes Retrieved by SiteMapDataSource Web Server Controls
Provides steps for how to selectively display only some paths through your Web site.
Appearance
ASP.NET Themes and Skins Overview
Provides information on themes and skins, including what they are and how ASP.NET uses them to create a consistent look
for pages and controls.
How to: Define ASP.NET Page Themes (Visual Studio)
Provides steps for how to create a collection of control properties and styles that you can apply as a unit to pages or Web
sites.
How to: Apply ASP.NET Themes
Provides steps for how to apply an existing theme to pages or to a Web site.
How to: Apply ASP.NET Themes Programmatically
Provides steps for how to apply a theme in code.
How to: Disable ASP.NET Themes
Provides steps for how to prevent a theme from being applied to an individual page or to a Web site.
User Profiles
ASP.NET Profile Properties Overview
Provides an introduction to using ASP.NET profiles to gather information from users and store it for use each time they visit.
User Identification for ASP.NET Profile Properties
Provides information on how individual Web sites are identified, whether users visit anonymously or log in.
Defining ASP.NET Profile Properties
Provides information on how to create profile information for individual users.
Securing Profile Properties
Provides information on reducing the security vulnerability of maintaining profile properties.
Programming
How to: Create ASP.NET Application-Level Event Handlers
Provides steps for how to create code that runs each time the Web site starts or each time a page request is received.
Deploying
Web Site Deployment in Visual Web Developer
Provides information on options for making your Web site available on a production Web server.
How to: Copy Web Site Files with the Copy Web Site Tool
Provides steps for how to copy files to another server and synchronize local and remote versions of a Web site.
How to: Publish Web Sites (Visual Studio)
Provides steps for how to precompile your Web site and store the compiled version on a staging server or production server.
Accessibility
Accessibility Support in ASP.NET
Provides information on features of ASP.NET that help you create Web sites that conform to accessibility standards.
How to: Check Accessibility of Web Pages in Visual Web Developer
Provides steps for how to use a Visual Web Developer tool to review your Web pages for accessibility.
Configuring
How to: Add a Reference to a .NET or COM Component in a Web Site
Provides steps for how to make a .NET Framework or COM component available to code in your Web site.
How to: Add a Reference to a Visual Studio Project in a Web Site
Provides steps for how to make the output of another Visual Studio project (such as a component) available to code in your
Web site.
How to: Add and Remove Web References
Provides steps for how to make an XML Web service available to code in your Web site.
How to: Configure Published Web Sites
Provides steps for how to examine and change the configuration settings of a Web site after it is published.
How to: Configure ASP.NET Applications for an ASP.NET Version
Provides steps for how to set ASP.NET to use a specific version of the .NET Framework.
How to: Configure XHTML Rendering in ASP.NET Web Sites
Provides steps for how to configure ASP.NET controls so they render markup that conforms to specific XHTML standards.
Converting from Visual Studio .NET
Web Project Conversion from Visual Studio .NET
Provides an overview of converting Visual Studio .NET 2003 Web projects to Visual Web Developer.
Web Solution and Project File Conversion
Provides details about changes made to pages and to other files during conversion.
Web Project Settings Conversion
Provides information about what the conversion process does with project settings.
Troubleshooting Conversion to Visual Web Developer
Provides information about problems that might arise during conversion.
See Also
Concepts
How Do I in Visual Web Developer
Visual Web Developer

ASP.NET Web Sites (Visual Studio)


This section features content and topics related to creating ASP.NET Web sites in Visual Web Developer.
In This Section
Getting Started - Creating Web Sites
Provides essential information about how to create ASP.NET Web sites.
Learning More - Creating Web Sites
Provides in-depth information about working with ASP.NET Web sites.
Walkthrough Topics — ASP.NET Web Sites
Provides links to tutorials about creating ASP.NET Web sites in Visual Web Developer.
How-to Topics — ASP.NET Web Sites
Provides links to how-to topics about creating ASP.NET Web sites in Visual Web Developer.
Related Sections
Guided Tour of Creating Web Sites in Visual Web Developer
Provides links to tutorials on all aspects of creating ASP.NET Web sites and Web pages.
Visual Web Developer

Getting Started - Creating Web Sites


This section includes topics that provide an overview of creating different types of Web sites, working with Web servers and
Visual Web Developer, and testing Web sites.
In This Section
Types of Web Sites in Visual Web Developer
Local IIS Web Sites
File System Web Sites
FTP-Deployed Web Sites
Remote IIS Web Sites
Building Web Sites
How to: Add Files to ASP.NET Web Sites
Web Servers in Visual Web Developer
Using Visual Web Developer as a Non-Administrative User
Related Sections
ASP.NET Web Pages (Visual Studio)
Provides information about creating ASP.NET Web pages in Visual Web Developer.
Visual Web Developer

Types of Web Sites in Visual Web Developer


Describes how files are stored on your Web site, using either file-system based Web sites or those that require Internet
Information Services (IIS).
You can use Visual Studio to create and work with ASP.NET Web sites (which are also known as Web applications) in a variety
of configurations: local IIS sites, file-system sites, File Transfer Protocol (FTP)–deployed sites, and remote sites. For guidelines to
help you decide when to use each type of Web site, see the table in Choosing a Web Site Type later in this topic.
Local IIS Web Sites
Local IIS Web sites run using a copy of IIS that is installed on your computer. When you create a local IIS Web site, the pages
and folders for your site are stored in a folder under the default IIS folder for Web sites, which is located at
[drive]:\Inetpub\wwwroot. Visual Studio also creates the appropriate IIS configuration so that the Web site is recognized by IIS
as an application.
Note
To create a local IIS Web site, you need to have administrative privileges on the computer.

Alternatively, you can create an IIS virtual directory in Visual Studio. In this case, the pages and folders for your Web site can be
in any folder to which users have access, and a virtual directory in your local copy of IIS must point to the file location. For
more information, see ASP.NET Required Access Control Lists (ACLs).
Note
If you create a Web site whose name contains non-ANSI characters on IIS 5.1 or earlier, you will not be able to browse to the
site because those versions of IIS do not resolve URLs that contain non-ANSI characters.

File-System Web Sites


In a file-system Web site, you can create and edit files in any folder you like, whether on your local computer or in a folder on
another computer that you access via network share. You are not required to run IIS on your computer. Instead, you can test
pages by using the ASP.NET Development Server. For details, see Web Servers in Visual Web Developer.
Note
The ASP.NET Development Server cannot serve pages to another computer. Therefore, it is suitable only for testing pages loc
ally.

In a file-system Web site, static files, such as images and style sheets, are subject to ASP.NET authorization rules. For example,
static files in a file-system Web site will not be served to an anonymous user when anonymous access to those files is disabled.
However, when you create a Web site project in an HTTP location, IIS serves static files without using authorization rules.
You can create a file-system Web site and later create an IIS virtual directory that points to the folder containing your pages.
For details, see How to: Create IIS Virtual Directories in Visual Web Developer.
FTP-Deployed Web Sites
Visual Studio allows you to open and edit Web sites that are available on an FTP server. This is a typical scenario if your Web
site is located on a hosting site.
You can connect from within Visual Studio to any FTP server on which you have Read/Write permissions. You can then create
and edit Web pages on that server. If the FTP server is configured with ASP.NET and an IIS virtual root that points to the FTP
directory, you can also run your pages from the server to test them. For more information, see
Walkthrough: Editing Web Sites with FTP in Visual Web Developer.
Remote Web Sites
A remote Web site is a site that uses IIS but is on another computer that you can access over a local area network. The remote
computer must have IIS installed and be configured with FrontPage 2002 Server Extensions from Microsoft. When you create a
remote Web site, the pages and folders for your site are stored under the default IIS folder on the remote computer, which is
located at [drive]:\Inetpub\wwwroot. When you run the pages, they are served using IIS on the remote computer. This is the
model used in Visual Studio .NET 2002 and Visual Studio .NET 2003. For more information, see What's New in Web Projects.
Note
If you create a Web site whose name contains non-ANSI characters on IIS 5.1 or earlier, you will not be able to browse to the
site because those versions of IIS do not resolve URLs that contain non-ANSI characters.

Choosing a Web Site Type


The following table summarizes the types of Web sites that you can create in Visual Studio, which you can use when deciding
which type of Web site meets your needs.
Web site ty Summary
pe
Local IIS We Use a local IIS Web site when you want to create Web pages on your local computer and you have IIS installed.
b site
Advantages:
The site is accessible from other computers.
You can test with IIS features, such as HTTP-based authentication, application pooling, and ISAPI filters.
Disadvantages:
You must have administrative rights to create or debug an IIS Web site.
Only one user on the computer can debug an IIS Web site at one time.
By default, remote access is enabled for a local IIS Web site.

File-system Use a file-system Web site when you want to create Web pages on your local computer or on a shared drive and
Web site you do not have IIS installed.
Note
You can create a file-system Web site and later create an IIS virtual directory that points to the folder containing
your pages.

Advantages:
The site can be accessed only from the local computer, reducing security vulnerabilities.
You do not need to have IIS installed on your computer.
You do not need administrative rights to create or debug a local file-system Web site.
If the computer is configured to allow remote desktop connections, multiple users can create and debug loc
al file-system Web sites at the same time.
Disadvantages:
You cannot test a file-system Web site with IIS features, such as HTTP-based authentication, application pool
ing, and ISAPI filters.
FTP-deploy Use an FTP-deployed Web site when your site already exists on a remote computer that has been configured as a
ed Web site n FTP server. (For example, your Internet service provider (ISP) has provided space on a server.)
Advantages:
You can test the FTP-deployed Web site on the server where it will be deployed.
Disadvantages:
You do not have local copies of the FTP-deployed Web site files unless you copy them yourself.
You cannot create an FTP-deployed Web site — you can only open one.

Remote We Use a remote Web site when you want to create a Web site by using IIS running on a remote computer. The remo
b site te computer must be configured with FrontPage Server Extensions.
Advantages:
You can test the Web site on the server where it will be deployed.
Multiple developers can work with the same remote Web site at the same time.
Disadvantages:
Configuration for debugging a remote Web site can be complex.
Only one developer can debug the remote Web site at one time. All other requests are suspended while the
developer is stepping through code.

See Also
Tasks
How to: Create File System Web Sites
How to: Create IIS Virtual Directories in Visual Web Developer
Walkthrough: Creating a Basic Web Page in Visual Web Developer
Walkthrough: Creating a Local IIS Web Site in Visual Web Developer
Walkthrough: Editing Web Sites with FTP in Visual Web Developer
Concepts
File System Web Sites
Visual Web Developer

Visual Web Developer Starter Kits


The ASP.NET 2.0 Starter Kits are sample ASP.NET Web sites that provide code to accomplish common Web development tasks.
Each sample is complete and well documented so that you can use the code to quickly start your ASP.NET development
projects today. Some samples were created when Visual Studio 2005 was released and, through the support of the ASP.NET
community, more samples have been added.
Note
The ASP.NET 2.0 Starter Kits are unsupported samples. As a result, Microsoft Product Support Services cannot answer questi
ons about the starter kits. However, you can post questions about the starter kits on the ASP.NET forums Web site, where co
mmunity members who have experience with the kits can help you.

Starter Kits
The following table lists some of the many starter kits that are available on the
ASP.NET 2.0 Starter Kits for Visual Web Developer 2005 Web site.
Starter kit Description
Personal Web The Personal Web Site Starter Kit provides a typical, personal site that includes a photo album system. The kit a
Site Starter Kit lso includes static pages for a resume and additional links. The site background is available in your choice of w
hite or black; just change the theme.

Club Site Start The Club Site Starter Kit provides a starting point for creating an ASP.NET Web site for your club or organizatio
er Kit n. This kit includes news posting, calendar, member directory, and photo album systems.

Time Tracker S The Time Tracker Starter Kit demonstrates how to build a line-of-business ASP.NET application that enables yo
tarter Kit u to track the period of time spent working on projects. You can use this kit to create projects, create task categ
ories, log completed work, and track time that was spent.

PayPal-enable The PayPal-enabled eCommerce Starter Kit is an extensible, open-source ASP.NET application that makes it eas
d Ecommerce y for you to set up and manage your own e-commerce Web site.
Starter Kit

eBay Selling St The eBay Selling Starter Kit for Microsoft Visual Basic provides a full-featured ASP.NET application for eBay auc
arter Kit tion management. You can customize the application to add new features, and you can integrate the applicatio
n with your existing inventory management system.

See Also
Concepts
Types of Web Sites in Visual Web Developer
Other Resources
ASP.NET Web Sites (Visual Studio)
Visual Web Developer

Local IIS Web Sites


A local Internet Information Services (IIS) Web site is an IIS Web application on your computer. Visual Web Developer
communicates with the Web site by using the HTTP protocol.
Creating or opening a local IIS Web site is useful in the following situations:
You want to test your Web site using IIS, which closely emulates how the Web site will run on a production server. This
can have advantages over working with file system Web sites that run using the ASP.NET Development Server, because
paths are resolved as they will be on a production server.
You already have a set of Web site files in a folder and you want to test the Web site with IIS. In this case, you can create a
virtual directory in your local version of IIS.
Your local computer is also your Web server.
Requirements
To create a local IIS Web site requires the following:
Your computer must have at least IIS version 5.0 installed and running.
Your computer must be running the .NET Framework version 2.0.
ASP.NET version 2.0 must be enabled in IIS. For details, see the topic "Enabling ASP.NET" in the
IIS Product Documentation.
You must be logged in as a user with administrative privileges. This is required because working with the IIS metabase
(where information about IIS applications is stored) requires administrative privileges.
To open an existing local IIS Web site, the preceding must be true as well as the following:
The site to be opened must be configured as an IIS application. For more information, see the topic "Creating Virtual
Directories in IIS 6.0" in the IIS Product Documentation.
The site must be configured to use ASP.NET version 2.0. If it is not, when you open the site, Visual Web Developer will
prompt you to reconfigure the site to use ASP.NET 2.0. This is distinct from having ASP.NET 2.0 installed on the
computer. It is possible to have ASP.NET 2.0 installed on the computer but have the site to be opened still mapped to use
an earlier version of ASP.NET. For details, see How to: Configure ASP.NET Applications for an ASP.NET Version.

Creating or Opening Local IIS Web Sites


When you create the Web site, Visual Web Developer performs all of the tasks that are required to make the Web site function
as an IIS application. Visual Web Developer creates the folder or folders for your Web site under the Web root for IIS (for
example, under \inetpub\wwwroot). After creating folders, Visual Web Developer creates the files for the Web site template
that you selected.
Note
You can create an IIS application as a subfolder of any existing IIS folder.

Local IIS Web Site Projects


When you create or open a local IIS Web site, Visual Web Developer creates a project to manage the files. The project stores a
small amount of information, such as your choices for how to run the application and what debuggers are available. Project
information is stored on a per-user basis. For more information, see Web Site Projects and Solutions.
Running Local IIS Web Sites
By default, when you run a local IIS Web site to test it, Visual Web Developer launches a browser and runs the Web site using
the server name localhost. For example, if you have created the Web site ExampleSite, when you test it in Visual Web
Developer, the browser will request the test page from this URL:

http://localhost/ExampleSite/page
IIS resolves the application name, whether it points to a folder that is under the IIS root or to another location, and serves
pages from that folder.
For more information, see Testing Web Pages in Visual Web Developer.
Deploying Local IIS Web Sites
Local IIS Web sites are generally used only for development, so that individual developers can create and test ASP.NET Web
pages on their own computers. In most cases, you must deploy the files from a file system Web site to a production server that
is running IIS.
You can deploy the files from a local IIS Web site using the Copy Web tool and the Publish Web utility in Visual Web
Developer. For details, see Web Site Deployment in Visual Web Developer.
Note
The Publish Web utility is not available in Visual Web Developer Express Edition.

See Also
Tasks
How to: Create Local IIS Web Sites
Concepts
Types of Web Sites in Visual Web Developer
Web Servers in Visual Web Developer
Visual Web Developer

Walkthrough: Creating a Local IIS Web Site in Visual Web


Developer
In the Microsoft Visual Web Developer Web development tool, you can create and edit Web sites that keep the Web pages and
other files in different locations. Your choices for locating Web pages and other files include the following:
In a folder on the local hard disk, which is referred to as a file system Web site.
As a Web application under a local copy of Microsoft Internet Information Services (IIS), which is referred as a local IIS
Web site.
You can also work with Web sites on a remote server by creating a Microsoft SharePoint Services Web site or by connecting to
a server that uses FTP. For more information, see Types of Web Sites in Visual Web Developer.
In this walkthrough, you will work with two Web sites that run under a locally installed copy of IIS. One of the Web sites is
physically located under the root folder of IIS (typically C:\Inetpub\wwwroot). A second Web site is located in a convenient
folder on the hard disk but the second Web site is available to IIS by using a virtual directory.
You can use IIS to test the Web site. If the computer is configured to permit other users to connect to it, the Web site is
available to those users.
Note
If you cannot run IIS on the computer, you can still create and test ASP.NET Web sites by running Visual Web Developer. For
more information, see Walkthrough: Creating a Basic Web Page in Visual Web Developer.

Tasks illustrated in this walkthrough include the following:


Creating an application and page under the IIS root.
Creating an application that uses an IIS virtual root.
Using IIS to run the page.
Working with IIS in Solution Explorer.
Prerequisites
To complete this walkthrough, you must have IIS installed locally on the computer, and you must be logged in as a user with
administrative privileges. This is required because working with the IIS metabase (where information about IIS applications is
stored) requires administrative privileges.
Creating a Web Site under the IIS Root
In the first part of the walkthrough, you will create a Web site that resides under the IIS default folder (typically
\Inetpub\wwwroot).
To create a new local IIS Web site under the IIS root
1. Open Visual Web Developer.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears.
3. Under Visual Studio installed templates, click ASP.NET Web Site.
4. Click Browse.
The Choose Location dialog box appears.
5. Click Local IIS.
6. Click Default Web Site.
7. Click the Create new Web program icon, which is located in the upper-right corner.
This icon is not labeled, but when you pause the mouse pointer on it, the Create New Web Application ToolTip text
appears.
A new application, named WebSite, is added under Default Web Site.
8. In the box for the new Web site, type LocalIISWebSite, and then click Open.
The New Web Site dialog box appears with the right-most Location box filled in with
http://localhost/LocalIISWebSite.
9. In the Language list, click the programming language that you prefer to work in.
The programming language that you choose will be the default for the Web site. However, you can use multiple
languages in the same Web application by creating pages and components in different programming languages.
10. Click OK.
Visual Web Developer creates the new Web site and opens a new page named Default.aspx. Keep this page open. This
initial Default.aspx page uses the Web page code-behind model. For more information, see
ASP.NET Web Page Code Model.
Visual Web Developer not only creates the folders and files for the Web site but it also interacts with IIS to create an IIS Web
application for your site. Essentially, Visual Web Developer calls IIS to create the metadata that IIS requires in order to be able
to recognize your folder and pages as a Web site.
You can examine what Visual Web Developer has performed by looking at the files and folders that have been created.
To examine the structure of the local IIS Web site
1. In Microsoft Windows, click Start, and then click Run.
In the Run dialog box, in the Open box, enter C:\Inetpub\wwwroot, and then click OK.
Note
If IIS is installed on a different drive or folder, change the path, as appropriate.

Under \wwwroot, you now see a new folder named LocalIISWebSite.


2. In the Path dialog box, double-click LocalIISWebSite.
You see the contents of the Web site, which include the following:
An App_Data folder, which is created automatically by Visual Web Developer.
A Default.aspx page.
The code-behind file, which is Default.aspx.cs or Default.aspx.vb, depending on the default language for the Web
application.
You can add pages to the Web site as you would ordinarily. However, you can also add pages to the Web site externally and
Visual Web Developer will recognize them as part of the application, although you might have to update Solution Explorer in
order to see them.
Adding and Programming Controls
In this part of the walkthrough, you will add a Button, TextBox, and Label control to the page and write code to handle the
Click event for the Button control.
To add controls to the page
1. In Visual Web Developer, open or switch to the Default.aspx page, and then switch to Design view.
2. Press SHIFT+ENTER several times to make some room.
3. From the Standard group in the Toolbox, drag three controls onto the page: a TextBox, Button, and Label.
Note
If you cannot see the Toolbox, on the View menu, click Toolbox.

4. Position the insertion pointer in front of the text box, and then type Enter your name:.
5. Click the Button control, and then in Properties, set Text to Display Name.
6. Click the Label control, and then in Properties, clear Text.
7. Double-click the Button control, which is now labeled Display Name.
Visual Web Developer opens the code file for the page in a separate window in the editor.
The file contains a skeleton Click handler for the Button control.
8. Complete the Click handler by adding the following highlighted code that will display the text string after the Button
control is clicked.
Security Note
User input in an ASP.NET Web page can include potentially malicious client script. By default, ASP.NET pages check pag
es on postback to guarantee that user input does not include script or HTML elements. For more information, see
Script Exploits Overview.

VB
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handl
es Button1.Click
Label1.Text = Textbox1.Text & ", welcome to Visual Web Developer!"
End Sub

C#
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = TextBox1.Text + ", welcome to Visual Web Developer!";
}

9. Save the files.


You will test this Web page in "Testing the IIS Web Application," later in this walkthrough.
Updating the Web Site Outside Visual Web Developer
You can see that Visual Web Developer is reading the IIS path by adding a new file to the application from outside Visual Web
Developer.
To update the Web outside Visual Web Developer
1. Using Notepad or another text editor, create a new file that contains the following text, depending on whether you are
using Visual Basic or C#.
VB
<%@Page language="VB"%>
<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handl
es Button1.Click
Button1.Text = "I was clicked!"
End Sub
</script>
<html>
<body>
<form runat="server" id="form1">
<asp:button runat="server" text="Button1" Id="Button1"
OnClick="Button1_Click"></asp:button>
</form>
</BODY>
</HTML>

C#
<%@Page language="C#"%>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
Button1.Text = "I was clicked!";
}
</script>
<html>
<body>
<form runat="server" id="form1">
<asp:button runat="server" text="Button1" Id="Button1"
OnClick="Button1_Click"></asp:button>
</form>
</BODY>
</HTML>

2. Save the file in the path C:\inetpub\wwwroot\LocalIISWebSite under the name TestPage.aspx.
Note
If IIS is installed on a different drive or folder, change the path, as appropriate.

3. In Visual Web Developer, in Solution Explorer, click the Web site name (http://localhost/LocalIISWebSite/), and then
on the View menu, click Refresh.
The list of files that are in the Web site is updated to include the file that you added. Next, you will test the Web pages.
Testing the IIS Web Application
You can now test the Web site.
To test the local IIS Web site
1. In Visual Web Developer, open the Default.aspx page.
2. Press CTRL+F5 to run the page.
The page opens in the browser. Notice that the URL in the browser is http://localhost/LocalIISWebSite/default.aspx.
The request for the page is being made to localhost (without a port number), which is handled by IIS.
3. When the page appears in the browser, in the text box, enter your name, and then click Display Name to make sure it is
working.
4. In Visual Web Developer, open the TestPage.aspx page.
5. Press CTRL+F5 to run the page.
The page opens in the same instance of the browser.
6. When the page appears in the browser, click Button1 to make sure it is working.
7. Close the browser.
If you can connect to the computer from another computer, you can try accessing your site as if it were a public site. If you
cannot connect to the computer from another computer, you can skip this procedure.
To test your site as a public site
From a different computer, type the URL that includes the Web server computer name, Web site name, and default.aspx
as the page:
If the computer can be accessed over a local area network, use the computer name for the server that has a URL
such as the following:
http://server1/LocalIISWebSite/default.aspx
If you host a domain on the computer, you can access the page using a URL such as the following:
http://www.contoso.com/LocalIISWebSite/default.aspx
If the computer is either on a network or directly connected to the Internet, you can use the IP address for the
computer as the server name. For example:
http://172.19.195.700/LocalIISWebSite/default.aspx
Note
If you are not able to view your application from a different computer because of the Windows Firewall settings, you m
ight have to enable the Web server on port 80. You can do this on the Advanced tab of Windows firewall by clicking S
ettings. For more information, go to Security Developer Center -- .NET Framework Security and search for information
about Windows firewall settings.

Creating a Web Site as an IIS Virtual Root


As you have seen up to this point, IIS lets you create Web applications that are physically located under the default Web server
root folder (wwwroot). However, you can also create IIS virtual directories, which are IIS Web applications that point to files and
folders that can be located anywhere on the hard disk.
Note
For security reasons, IIS does not let you create virtual directories that point to folders on other computers. Virtual directories
must always point to the local computer.

In this part of the walkthrough, you will use Visual Web Developer to create a virtual directory that points to a Web site that is
stored in a local folder on the computer.
The first step is to create the virtual directory. If you have already created a file system Web site in Visual Web Developer (for
example, by completing Walkthrough: Creating a Basic Web Page in Visual Web Developer), you can use that Web site.
To create a local IIS Web site using a virtual folder
1. In Visual Web Developer, on the File menu, click New Web site.
2. Under Visual Studio Installed Templates, click ASP.NET Web Site.
3. Click Browse.
The Choose Location dialog box appears.
4. Click Local IIS.
5. Under Select the Web site you want to open, in the tree view, click Default Web Site, and then click the Create new
virtual directory icon, which is located in the upper-right corner.
This icon is not labeled, but when you pause the mouse pointer on it, the Create New Virtual Directory ToolTip text
appears.
The New Virtual Directory dialog box appears.
6. In the Alias Name box, type WebSite_vdir.
Note
You can name your virtual directory anything that you like, as long as you use a name that is valid in IIS.
7. In the Folder box, type one of the following:
The path of an existing file system Web site, if you have one. You can click Browse, and then locate the root folder
of that site, if you do not remember the exact path.
The path where you want to create a new folder to store the folders and files for the Web site.
8. Click OK.
If you specified a folder that does not exist, Visual Web Developer prompts you to create it.
Visual Web Developer then returns to the Choose Location dialog box and updates the list of IIS Web applications that
have the virtual directory that you created.
9. Select the virtual directory that you just created, click Open, and then click OK to create the Web site.
If you pointed the virtual directory to a new folder or an existing folder that does not contain a Web site, Visual Web
Developer creates the App_Data folder, a default page, and opens the page in the designer.
If your virtual folder points to an existing file system Web site, Visual Web Developer opens a Web Site Already Exists
dialog box and gives you the option to select a new folder, open the existing site, or create a new Web site in the existing
location. After you select your option and click OK, Visual Web Developer displays the contents of the folder in Solution
Explorer and opens the Default.aspx page, if it exists.
Adding Controls to the Web Page
As you did in " Testing the IIS Web Application," earlier in this walkthrough, you will use a simple ASP.NET Web page to test the
IIS Web site that you are creating. If you are working with an existing file system Web site, you do not have to create a new
page. If your virtual directory points to a new folder, you can use that page.
If this is a new Web site, you will add some controls to the default page so that you can test that the page is working correctly.
To add controls to the page
1. In Visual Web Developer, open the Default.aspx page and switch to Design view.
2. From the Standard group in the Toolbox, drag a TextBox, Button, and Label control onto the page.
3. Double-click the Button control, and then add the following highlighted code:
VB
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handl
es Button1.Click
Label1.Text = "Welcome to Visual Web Developer!"
End Sub

C#
protected void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text = "Welcome to Visual Web Developer!";
}

4. Save the files.


Testing the Virtual Directory
You can now test the Web site.
To test the local IIS Web site using the virtual directory
1. In Visual Web Developer, open a page in the Web site, which can be the Default.aspx page or another page.
2. Press CTRL+F5 to run the page.
The page opens in the browser. Notice that the URL in the browser is http://localhost/Website_vdir/default.aspx.
When IIS resolves the URL, it looks up the physical path that is associated with the virtual directory named Website_vdir
and looks for the page there.
3. When the page appears in the browser, click the Button control to make sure it is working.
4. Close the browser.
If you can connect to the computer from another computer, you can try the same tests that you used in the preceding section
to try accessing the page.
Deleting a Local IIS Web Site
You can manage local IIS Web sites in Visual Web Developer by deleting ones that you no longer need. There is an important
difference in how deletion works, depending on which type of local IIS Web site that you are working with, as follows:
When you delete a Web site under the IIS root, the Web application is deleted from IIS and the files and folders for the
Web site are deleted also.
When you delete a virtual directory, the IIS information about that Web site is deleted but the files and folders in the local
file system folder are left intact.

To delete the local IIS Web site


1. On the File menu, click Close Solution or Close Project.
2. On the File menu, click Open Web site.
3. In the Open Web Site dialog box, click Local IIS.
4. Click the name of the virtual directory (Website_vdir) that you created in "Creating a Web Site as an IIS Virtual Root,"
earlier in the walkthrough.
Caution
If you select a different Web site, the files and folders for that Web site might be deleted.

5. Click the delete icon in the upper-right corner.


This icon is not labeled, but when you pause the mouse pointer on it, the Delete ToolTip text appears.
6. When you are prompted for confirmation to delete the Web site, click Yes.
7. Click Cancel to close the Open Web Site dialog box.
8. Open the browser, and then type the URL for the virtual directory:
http://localhost/Website_vdir/default.aspx
This time, the browser reports that the page cannot be found, because IIS no longer recognizes Website_vdir as a Web
site on the local computer.
Note
It is possible that the page was cached by the local browser. In that case, the page might still display until you flush the
browser cache, and then try to view the page again.

Next Steps
In this walkthrough, you have learned how to create a Web site using the local copy of IIS. You might also want to learn about
other types of Web sites that you can create in Visual Web Developer. For example, you might want to do the following:
Create a file system Web site, where the pages are stored in a folder anywhere on the hard disk.
For more information, see Walkthrough: Creating a Basic Web Page in Visual Web Developer.
Learn how to use FTP to open and edit Web sites.
For more information, see Walkthrough: Editing Web Sites with FTP in Visual Web Developer.
See Also
Concepts
Types of Web Sites in Visual Web Developer
Using Visual Web Developer as a Non-Administrative User
Visual Web Developer

How to: Create Local IIS Web Sites


A local Internet Information Services (IIS) Web site is an IIS Web application on your computer. Visual Web Developer
communicates with local Web sites by using the HTTP protocol. You can create a new local IIS Web site that uses files in the
following ways:
You can create a new IIS application, which creates a new folder and files under the IIS root.
You can create a Web site that points to an existing IIS application, and then edit the files in that application.
You can create a new virtual directory, which creates a new IIS application that points to files that are in a folder other
than the IIS root. You can either create a new folder or point to a folder that already contains files.
To create a local IIS Web site requires the following:
IIS version 5.0 or later must be installed on your computer and must be running.
You must be logged in as a user with administrative privileges. This is required because working with the IIS metabase
(where information about IIS applications is stored) requires administrative privileges.
ASP.NET 2.0 must be enabled on IIS. For details, see the topic Enabling ASP.NET in the IIS documentation at
IIS 6.0 Product Documentation.
To open an existing local IIS Web site, the preceding must be true, and in addition:
The site to be opened must be configured as an IIS application. For more information, see
Creating and Isolating Applications in IIS 6.0 in the IIS 6.0 Operations Guide.
The site must be configured to use ASP.NET 2.0. If it is not, when you open the site, Visual Web Developer will prompt
you to reconfigure the site to use ASP.NET 2.0.
Note
Static files, such as images and style sheets, are not subject to ASP.NET authorization when they are served through IIS. Use II
S security features to restrict access to static files if they are not meant for all users. If you use the ASP.NET Development Ser
ver to test your ASP.NET application, the application will behave differently. This is because static files are subject to ASP.NET
authorization and will not be served to an anonymous user when anonymous access to those files is disabled.

To create a local IIS Web site


1. In Visual Web Developer, on the File menu click New Web Site.
2. Under Visual Studio Installed Templates, select the template for the type of Web site that you want to create.
3. To create a Web site directly, do the following:
a. In the Location list, click HTTP.
b. In the location box, type the URL of the site to create in the following format: http://localhost/SiteName.
c. Click OK.
Alternatively, follow the remaining steps in this procedure to create a Web site based on an existing IIS application or to
create a site that uses a virtual directory.
4. Click Browse.
5. In the Choose Location dialog box, click the Local IIS tab.
6. In the tree, open the node for the IIS Web site where you want to create yo