SlideShare a Scribd company logo
1 of 114
Walkthrough: Creating a Basic
Web Forms Page in Visual
Studio
Other Versions
This walkthrough provides you with an introduction to the Web development environment in Visual
Studio and in Visual Web Developer Express for ASP.NET Web Forms pages. This walkthrough guides you
through creating a simple ASP.NET Web Forms page and illustrates the basic techniques of creating a new
page, adding controls, and writing code.
Note
This topic applies only to ASP.NET Web Forms pages. It does not apply to pages that you create
using ASP.NET MVC (Model View Controller) or ASP.NET Web Pages.
Tasks illustrated in this walkthrough include:
 Creating a file system Web site project.
 Familiarizing yourself with Visual Studio.
 Creating a single-file ASP.NET Web Forms page.
 Adding controls.
 Adding event handlers.
 Running pages by using the Web server that is built into Visual Studio for testing.
Prerequisites
In order to complete this walkthrough, you will need:
 Visual Studio or Visual Web Developer Express. For download information, see the Visual Studio
Development Center Web site.
Note
If you are using Visual Studio, this walkthrough assumes that you selected the Web
Developmentcollection of settings the first time that you started Visual Studio. For more
information, see How to: Select Web Development Environment Settings.
 The .NET Framework, which is installed when you install Visual Studio or Visual Web Developer
Express.
Creating a Web Site Project and a Web Forms Page
In this part of the walkthrough, you will create a Web site project 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 project 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 project is one that stores pages and other files in a folder that you choose
somewhere on your computer. Other Web project options include the following:
 A local IIS Web site project, which stores your files in a subfolder of the local IIS root (typically,
inetpubwwwroot).
 An FTP site project, which stores files on a remote server that you gain access to across the
Internet by using File Transfer Protocol (FTP).
 A remote IIS Web site project, which stores files on a remote server that you can access across a
local network.
 A Web application project, which is similar to a file system Web site project except you compile it
before deployment and deploy it as a dynamic link library (.dll) file. For more information about
the difference between Web site projects and Web application projects, see Web Application
Projects versus Web Site Projects in Visual Studio.
To create a file system Web site
1. Open Visual Studio or Microsoft Visual Web Developer Express.
2. On the File menu, click New Web Site.
The New Web Site dialog box appears, as shown in the following illustration:
3. Under Installed Templates, click Visual Basic or C# and then select ASP.NET Web Site.
When you create a Web site project, you specify a template. Each template creates a Web project
that contains different files and folders. In this walkthrough, you are creating a Web site based on
the ASP.NET Web Sitetemplate, which creates files and folders that are typically used in ASP.NET
Web sites.
4. In the Web 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:BasicWebSite.
5. Click OK.
Visual Studio creates a Web project that includes prebuilt functionality for layout (a master page,
the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script
files), and for authentication (ASP.NET membership). When a new page is created, by default
Visual Studio displays the page in Source view, where you can see the page's HTML elements.
The following illustration shows what you would see in Source view if you created a new Web
page named FirstWebPage.aspx.
A Tour of the Visual Studio Web Development Environment
Before you proceed with working on the page, it is useful to familiarize yourself with the Visual Studio
development environment. The following illustration shows you the windows and tools that are available
in Visual Studio and Microsoft Visual Web Developer Express.
Note
This diagram shows default windows and window locations. The View menu allows you to
display additional windows, and to rearrange and resize windows to suit your preferences. If
changes have already been made to the window arrangement, what you see will not match the
illustration.
The Visual Studio environment
To familiarize yourself with the Web designer
 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.)
o Toolbars. Provide commands for formatting text, finding text, and so on. Some toolbars
are available only when you are working in Design view.
o Solution Explorer window. Displays the files and folders in your Web site.
o Document window. Displays the documents you are working on in tabbed windows. You
can switch between documents by clicking tabs.
o Properties window. Allows you to change settings for the page, HTML elements, controls,
and other objects.
o 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. Split view
displays both the Designview and the Source view for the document. You will work with
the Design and Source 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.
o ToolBox. Provides controls and HTML elements that you can drag onto your
page. Toolboxelements are grouped by common function.
o Server Explorer/Database Explorer. Displays database connections. If Server
Explorer is not visible, on the View menu, click Server Explorer or Database Explorer.
Note
The Server Explorer window is named Database Explorer in Microsoft Visual
Web Developer Express. To see all available menu items in Microsoft Visual
Web Developer Express, on the Toolsmenu, click Settings, and then click Expert
Settings.
Creating a New ASP.NET Web Forms Page
When you create a new Web site using the ASP.NET Web Site project template, Visual Studio adds an
ASP.NET 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 that displays the file name and then
click Close.
2. In Solution Explorer, right-click the Web site (for example, C:BasicWebSite), and then click Add
New Item.
The Add New Item dialog box is displayed. The following illustration shows an example of
the Add New Item dialog box.
3. In the template list, select Web Form.
4. In the Name box, type FirstWebPage.
When you created the Web site project, you specified a default language based on the project
template that you selected. However, each time you create a new page or component for your
Web site, you can select the programming language for that page or component. You can use
different programming languages in the same Web site.
5. Clear the Place code in separate file check box.
In this walkthrough, you are creating a single-file Web Forms page with the code and HTML in the
same page. The code for ASP.NET Web Forms pages can be located either in the page or in a
separate class file.
6. Click Add.
Visual Studio creates the new page and opens it.
Adding HTML to the Web Forms 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 except for a dashed line that
outlines a rectangle. This rectangle represents a div element on the page.
2. Click inside the rectangle that is outlined by a dashed line.
3. Type Welcome to Visual Web Developer and press ENTER twice.
The following illustration shows the text you typed in Design view.
4. Switch to Source view.
You can see the HTML that you created by typing in Design view, as shown in the following
illustration.
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 Visual Studio Development Server, which runs locally and does not require IIS. For file system Web
site projects, the default Web server in Visual Studio and Microsoft Visual Web Developer Express is the
Visual Studio Development Server.
To run the page
1. In Solution Explorer, right-click FirstWebPage.aspx and select Set as Start Page.
2. Press CTRL+F5 to run the page.
Visual Studio starts the Visual Studio Development Server. An icon appears in the Windows
taskbar to indicate that the Visual Studio Development Server is running, as shown in the
following illustration.
The page is displayed in the browser. Although the page you created has a file-name extension of
.aspx, it currently runs like any HTML page.
To display a page in the browser you can also right-click the page in Solution Explorer and
select View in Browser.
3. Close the browser.
Adding and Programming Controls
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 Forms
pages. However, you can program the controls with code that runs on the server, not the client.
You will add a Button control, a TextBox control, and a Label control to the page and write code to handle
the Clickevent for the Button control.
To add controls to the page
1. Click the Design tab to switch to Design view.
2. Put the insertion point at the end of the Welcome to Visual Web Developer text and press
ENTER five or more times to make some room in the div element box.
3. In the Toolbox, expand the Standard group.
4. Drag a TextBox control onto the page and drop it in the middle of the div element box that
has Welcome to Visual Web Developer in the first line.
5. Drag a Button control onto the page and drop it to the right of the TextBox control.
6. Drag a Label control onto the page and drop it on a separate line below the Button control.
7. 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 illustration shows how the three controls appear
in Design view.
Setting Control Properties
Visual Studio 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. The text
you entered appears on the button in the designer, as shown in the following illustration.
Note
If the Properties window is not displayed, press F4 to display it.
2.
3. Switch to Source view.
Source view displays the HTML for the page, including the elements that Visual Studio 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 Buttoncontrol, 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".
Therunat="server" attribute and the asp: prefix for control tags mark the controls so that they
are processed by ASP.NET on the server when the page runs. Code outside of <form
runat="server"> and <script runat="server"> elements is sent unchanged to the browser,
which is why the ASP.NET code must be inside an element whose opening tag contains
the runat="server" attribute.
4. Put the insertion point after asp:Label in 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 illustration shows the IntelliSense
drop-down list for the Labelcontrol.
5. Select ForeColor and then type an equal sign and a quotation mark (=").
IntelliSense displays a list of colors.
Note
You can display an IntelliSense drop-down list at any time by pressing CTRL+J.
6. Select a color for the Label control's text. Make sure you select a color that is dark enough to read
against a white background.
The ForeColor attribute is completed with the color that you have selected, including the closing
quotation mark.
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 Studio 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 Designview is just one of several ways you can create event
handlers.
3. Inside the handler, type Label1 followed by a period (.).
When you type the period after Label, Visual Studio displays a list of available members for
the Labelcontrol, as shown in the following illustration.
4. Finish the Click event handler for the button so that it reads as shown in the following code
example.
C#
VB
protected void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text = TextBox1.Text + ", welcome to Visual Studio!";
}
5. Scroll down to the <asp:Button> element. Note that the <asp:Button> element now has the
attributeonclick="Button1_Click".
This attribute binds the button's Click event to the handler method you coded in the previous
step.
Event handler methods can have any name; the name you see is the default name created by
Visual Studio. The important point is that the name used for the onclick attribute must match the
name of a method in the page.
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 Visual Studio 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 Buttoncontrol'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 <input type="submit"> element.
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. TheCalendar 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 System.Web.UI.WebControls.Calendar control to the page and format it.
To add a Calendar control
1. In Visual Studio, switch to Design view.
2. From the Standard section of the Toolbox, drag a Calendar control onto the page and drop it
below the divelement that contains the other controls:
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 illustration shows
the Calendar control as rendered 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 illustration shows the 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 illustration shows the Calendar control
in Source view. (The exact markup that you see in Source view might differ slightly from the
illustration.)
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. In Design view, double-click the Calendar control.
A new event handler is created in Source view.
2. Finish the SelectionChanged event handler with the following highlighted code.
C#
VB
protected void Calendar1_SelectionChanged(object sender,
System.EventArgs e)
{
Label1.Text = Calendar1.SelectedDate.ToLongDateString();
}
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.
Visual Studio Templates for
Web Projects
.NET Framework 4.5
Visual Studio includes project templates to help you get started when you create a web project. You can
create web application projects or web site projects. By considering the most appropriate project type
before you begin, you can save time when you create, test, and deploy the web project.
Web Project Templates
From the File menu, you can select either New Project or New Web Site. The New Project dialog box
provides a list of web application templates. Use the web application project template to create web
applications that are compiled into an assembly and that provide rich options for deployment.
The New Web Site dialog box provides a list of web site templates. Use the Web Site project template
when you want to compile the source code dynamically. For more information about the differences
between web project types, see Web Application Projects versus Web Site Projects.
Note
You can install additional products by using the NuGet package manager. In some cases, these
products include additional templates for new projects. The lists in this topic show you only the
templates that are included by default with Visual Studio 2012.
Web Application Templates
Web application templates help you create a web project that is compiled into an assembly for
deployment. The following table lists templates that appear in the New Project dialog box under
the Web category after you select a language (Visual Basic or Visual C#).
Project Template More Information
ASP.NET Web
Forms
Application
Use this project template to create a web application that is based on
ASP.NET Web Forms pages and that includes the following functionality.
You can choose not to use any of these features when they are not required
for your application.
 A master page.
 A cascading style sheet.
 Login security that uses the ASP.NET membership system.
 Ajax scripting that uses jQuery.
 Navigation that uses a menu control.
By default, the ASP.NET Web Application project template includes the
following:
 Folders to contain membership pages, client script files, and
cascading style sheet files.
 A data folder (App_Data), which is granted permissions that allow
ASP.NET to read and write to it at run time.
 A master page (the Site.master file).
 Web pages named Default.aspx, Contact.aspx, and About.aspx.
These content pages are based on the default master.
 A global application class (Global.asax file).
 A Web.config file.
 A Packages.config file.
 For more information, see ASP.NET Web Application
Projects and Web Application Projects versus Web Site Projects in
Visual Studio.
ASP.NET MVC 3
Web Application
Use this project template to create web applications that use a model-view-
controller pattern, using the ASP.NET MVC 3 release. The MVC pattern
helps separate the different aspects of the application (input logic, business
logic, and UI logic), while providing a loose coupling between these
elements. In addition, this project template promotes test-driven
development (TDD).
For more information, see ASP.NET MVC Overview.
ASP.NET MVC 4
Web Application
Use this project template to create web applications that use a model-view-
controller pattern, using the ASP.NET MVC 4 release.
For more information, see ASP.NET MVC Overview.
ASP.NET Empty
Web Application
This template creates an ASP.NET web application that includes a
Web.config file, but no other files. Use this project template when you do
not require the functionality built into the standard template.
ASP.NET
Dynamic Data
Entities Web
Application
Use this project template to create a Dynamic Data web application that
uses the ADO.NET Entity Framework. This type of Dynamic Data web
application can target any relational database.
Dynamic Data automatically generates a functional web application for
viewing and editing data, based on the schema of the data. For more
information, see ASP.NET Dynamic Data Overview.
ASP.NET AJAX
Server Control
Use this project template to create a web server control for ASP.NET Web
Forms pages that incorporates Ajax functionality. The control consists of
server and client code that work together to produce rich client behavior.
For more information, see ASP.NET AJAX Overview.
ASP.NET AJAX
Server Control
Extender
Use this project template to create an Ajax component that enhances the
client capabilities of standard ASP.NET web server controls.
For more information, see ASP.NET AJAX Extender Controls Overview.
ASP.NET Server
Control
Use this project template to create a custom ASP.NET web server control
that can be used in ASP.NET Web Forms pages.
For more information, see Developing Custom ASP.NET Server Controls.
Web Site Templates
Web site templates help you create a web project that by default is compiled dynamically. The following
table lists templates that appear in the New Web Site dialog box.
Project
Template
More Information
ASP.NET Web
Forms Site
Use this project template to create a website that includes the following
functionality. You can choose not to use any of these features when they are
not required for your application.
 A master page.
 A cascading style sheet.
 Login security that uses the ASP.NET membership system.
 Ajax scripting that uses jQuery.
 Navigation using a menu control.
By default, the ASP.NET Web Site project template includes the following:
 Folders to contain membership pages, client script files, and
cascading style sheet files.
 A data folder (App_Data), which is granted permissions that allow
ASP.NET to read and write to it at run time.
 A master page (.master file).
 Web pages named Default.aspx and About.aspx. In the project
template, these pages are content pages that use default master page.
 A global application class (Global.asax file).
 A Web.config file.
For more information, see Walkthrough: Creating a Basic Web Page in
Visual Studio.
ASP.NET Web
Site (Razor v2)
Use this project template to create a website that uses ASP.NET Web Pages
version 2 with Razor syntax. For more information, see Introduction to
ASP.NET Web Programming Using the Razor Syntax.
ASP.NET Web
Site (Razor)
Use this project template to create a website that uses ASP.NET Web Pages
with the Razor syntax. For more information, see Introduction to ASP.NET
Web Programming Using the Razor Syntax.
ASP.NET Empty
Web Site
This template creates an ASP.NET website that includes a Web.config file
but no other files. Use this project template when you do not require the
functionality built into the standard.
ASP.NET
Dynamic Data
Entities Web Site
Use this project template to create a Dynamic Data website that uses the
ADO.NET Entity Framework. This type of Dynamic Data web application
can target any relational database.
Dynamic Data automatically generates a functional web application for
viewing and editing data, based on the schema of the data. For more
information, see ASP.NET Dynamic Data.
WCF Service Use this project template to create a Windows Communication Foundation
(WCF) service. You can extend the service so that a website, web
application, Silverlight application, Ajax application, or other client can call
it.
For more information, see Windows Communication Foundation.
ASP.NET
Reports Web Site
Use this project template to create an ASP.NET website that contains a
report (.rdlc file), a default ASP.NET Web Forms page (.aspx file) that
contains a ReportViewer control, and a Web.config file. For more
information, see Microsoft Reports.
Walkthrough: Creating a Basic
Web Forms Page with Code
Separation in Visual Studio
Other Versions
When you create ASP.NET Web Forms pages and write code in them, you can select from two models for
how to manage the visible elements (controls and 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 Forms pages that use code separation.
Note
This topic applies only to ASP.NET Web Forms pages. It does not apply to pages that you create
using ASP.NET MVC (Model View Controller) or ASP.NET Web Pages.
The single-file model is introduced in Walkthrough: Creating a Basic Web Forms Page in Visual Studio.
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 Studio 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.
Tasks illustrated in this walkthrough include:
 Creating an ASP.NET Web Forms page with code separation.
 Adding server controls.
 Adding event handlers.
 Running pages with the Visual Studio Development Server.
Prerequisites
In order to complete this walkthrough, you will need:
 Visual Studio or Visual Web Developer Express.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web
Developmentcollection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.
Creating a Web Site Project and Page
In this part of the walkthrough, you will create a Web site project 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 Forms Web site project in Visual Studio (for example, by following the
steps inWalkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and
skip to "Creating a New Page" later in this walkthrough. Otherwise, create a new Web site project and
page by following these steps.
To create a file system Web site project
1. Open Visual Studio or Visual Web Developer Express.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site.
4. In the Web location box, select File System, and then enter the name of the folder where you
want to keep the pages for your Web site.
For example, type the folder name C:WebSites.
5. Click OK.
Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master
page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client
script files), and for authentication (ASP.NET membership).
Creating a New Web Forms Page
When you create a new Web site project, Visual Studio adds a Web Forms page named Default.aspx. By
default, Visual Studio 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 then
click Close.
2. In Solution Explorer, right-click the Web site (for example, C:BasicWebSite) and then click Add
New Item.
3. Under Installed Templates, click Visual Basic or Visual C# and then select Web Form from the
list.
4. In the Name box, enter WebPageSeparated.
5. Make sure that the Place code in separate file check box is selected.
6. Make sure that the Select master page check box is cleared.
For this walkthrough, you will create a page that does not use the master page that is included in
the Web site project.
7. Click Add.
Visual Studio 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 Web Forms 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. Place the insertion pointer in the div element that is already on the page.
3. Type the words Welcome to Visual Studio Using Code Separation.
4. 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 Server Controls
In this part of the walkthrough, you will add server controls to the Web Forms page: a button, text box,
and label control. You will also 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 Forms 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. Place the insertion pointer after the text that you added previously.
3. Press ENTER a few times to make some room.
4. From the Standard tab in the Toolbox, drag three controls onto the page: a TextBox control,
a Button control, and a Label control.
5. 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 Server Control Properties
Visual Studio offers you various ways to set the properties of server 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 markup for the page, including the elements that Visual Studio
has created for the server controls. Server controls are declared using HTML-like syntax, except
that the tags use the prefix asp: and include the attribute runat="server".
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".
Therunat="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 Studio 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.
C#
VB
protected void Button1_Click(object sender, System.EventArgs e)
{
Label1.Text = TextBox1.Text + ", welcome to Visual Studio!";
}
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 Web Forms page named WebPageSeparated:
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.
C#
VB
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="WebPageSeparated.aspx.cs" Inherits="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 Web
Forms page. The Inherits attribute identifies the class defined in the code-behind file from which
the .aspx page is derived. By default, Visual Studio 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.
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 Visual Studio Development Server.
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
inWalkthrough: Creating a Basic Web Forms Page in Visual Studio 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 Forms 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 site projects using Microsoft Internet Information
Services (IIS), and FTP, and you can work with Web application projects. For details, see Types of
Web Site Projects in Visual Studioand Web Application Projects versus Web Site Projects in Visual
Studio.
 Add data access to Web Forms pages. For details, see Walkthrough: Basic Data Access Using the
SqlDataSource Control 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.
Walkthrough: Basic HTML
Editing in Visual Studio for Web
Forms Pages
.NET Framework 4.5
Other Versions
Microsoft Visual Studio 2012 provides a rich HTML editing experience for Web Forms pages. The Visual
Studio HTML editor lets you work in WYSIWYG mode and also lets you work directly with HTML markup
for finer control. This walkthrough introduces you to the HTML editing features of Visual Studio.
Note
This topic applies to ASP.NET Web Forms pages. You can use Source view for editing pages
in ASP.NET MVC (Model View Controller)or ASP.NET Web Pages applications (.cshtml files),
but Design view is fully supported only for Web Forms pages. Web server controls are used only
in Web Forms pages.
Tasks illustrated in this walkthrough include the following:
 Creating and editing HTML in Design view.
 Creating and editing HTML in Source view.
 Using Split view.
 Using navigation tools to move quickly through your HTML tags.
Prerequisites
In order to complete this walkthrough, you need the following:
 Visual Studio or Visual Studio Express for Web installed on your computer.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web
Developmentcollection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.
 A general understanding of how to work in Visual Studio.
For an introduction to how to create Web Forms pages in Visual Studio, see Walkthrough:
Creating a Basic Web Forms Page in Visual Studio.
Creating the Web Site and Web Forms Page
If you have already created a Web Forms site in Visual Studio or Visual Studio Express for Web (for
example, by completing Walkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use
that web site and go to the next section. Otherwise, create a website and Web Forms page by following
these steps.
Note
This walkthrough uses a web site project. You could use a web application project instead. For
information about the difference between these web project types, see Web Application Projects
versus Web Site Projects.
To create a file system website
1. Open Visual Studio or Visual Studio Express for Web.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed, click Visual Basic or Visual C# and then select ASP.NET Empty Web Site.
For this walkthrough, you create a website that does not include prebuilt pages and other
resources.
4. In the Web location box, select File System, and then enter the name of the folder where you
want to keep the pages for your website.
For example, type the folder name C:WebSites.
5. Click OK.
Visual Studio creates a website project that includes a Web.config file.
6. In Solution Explorer, right-click the root of your Web site, and then click Add New Item.
7. Select Web Form, name the file Default.aspx, and then click Add.
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 Web Forms 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 select it, and then on the Formatting toolbar click Heading 1.
4. Press ENTER after ASP.NET Web Page, and then type This page is powered by ASP.NET.
5. Highlight the text, then, on the Format menu, click New Style.
The New Style dialog box appears.
6. Select the Apply new style to document selection option.
7. Select a font from the font-family drop-down list and then click Apply.
The font family is applied to the selected text.
8. Under Category, click Block, and then select (value) from the line-height drop-down list. Enter a
value for line height.
9. Select (value) from the letter-spacing dropdown list. Enter a value for letter spacing.
Click Apply to see the values applied to the selected text.
10. Click OK.
Viewing Tag Information
When you are working in Design view, you might want to see tags such as div and span that do not have
a visual rendering.
To see HTML design surface tags in Design view
 On the View menu, point to Visual Aids, and make sure that ASP.NET Non-visual Controls is
selected.
The designer displays symbols for paragraphs, line breaks, and other tags that do not render text.
The symbols are not all shown at the same time, but when you click a visual element, the
nonvisual element that precedes it is shown.
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 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. Put the cursor to the right of the text 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 and drop it in
the space you created in the preceding step.
Note
You can also add a control by double-clicking it.
3.
4. Drag a Button control onto the page and drop it to the right of the TextBox control that you
added in the preceding step.
The TextBox and Button controls are ASP.NET web server controls, not HTML elements.
5. Put the cursor to the right of the Button control and then press ENTER.
6. On the Table menu, click Insert Table.
The Insert Table dialog box appears.
7. 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
the Properties window.
To set properties by using the Properties window
1. Select the Button control that you added in "Adding Controls and Elements" earlier in this
walkthrough.
2. In Properties window, set Text to Click Here, and ForeColor to a different color.
3. Place the cursor in the ASP.NET hyperlink that you created in the preceding section.
Notice that in the Properties window, the hreef 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 Studio starts IIS Express, which is a local web server that you can use to test pages without
using a full IIS server.
Note
You can run pages in several ways. If you press CTRL+F5, Visual Studio 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 Designview. You can also run pages in the debugger. For more
information, see Walkthrough: Debugging Web Pages in Visual Web Developer.
Changing the Default View
By default, Visual Studio opens new pages in Source view.
To change the default page view to Design view
1. On the Tools menu, click Options
2. Make sure that the Show all settings options is selected at the bottom of the dialog box.
3. Open the HTML Designer node and then select General. Under Start Pages in,
click Design view.
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 bottom 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 opening <asp:button> tag.
2. From the HTML group in the Toolbox (not the Standard group), drag a Table element onto the
page and place it just above the </form> tag.
The editor also helps you when you type markup manually. For example, the editor provides context-
sensitive choices that finish 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. You can see the
error or warning information by holding the mouse over the markup text.
To edit HTML in Source view
1. Position the cursor 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. Enter "a" to create an anchor tag, and then press the SPACEBAR.
The editor displays a list of attributes that are appropriate for an anchor tag.
Note
The letter a (anchor element) might not appear as an option, depending on the validation
target that is set for the site or the page. However, you can still create an anchor element
by entering "a" without selecting an item in the drop-down list. Validation targets are
discussed later in this topic.
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.
4. In the 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 by entering the text Home between the opening and closing tags.
The element now resembles the following example:
<a href="Default.aspx">Home</a>
6. Position the cursor 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.
7. 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. However, you can 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:
2. <asp:Button
3. id="Button1"
4. runat="server"
5. Font-Bold="True"
6. ForeColor="Blue"
7. Text="Click Here" />
Notice that after you indent the first attribute, when you press ENTER in the tag, subsequent lines
are indented to match.
8. Switch to Design view.
9. Right-click the Button control, and then click Copy.
10. Position the cursor below the Button control, right-click, and then click Paste.
Visual Studio creates a button with the ID property set to Button2.
11. From the Standard group in the Toolbox, drag a third Button control onto the page, which
creates a button named Button3.
12. Switch to Source view.
Notice that Button2 is formatted exactly the way that you formatted Button1. On the other
hand, Button3is formatted using the default formatting for Button controls.
Note
For more information on how to customize the formatting of individual elements,
see Walkthrough: Advanced HTML Editing in Visual Studio for Web Forms Pages.
13. Edit the document so that Button1 and Button2 are on the same line without a space between
them, as shown in the following example:
14. <asp:Button ID="Button1" runat="server" Font-Bold="True"
15. ForeColor="Blue" Text="Click Here" /><asp:Button ID="Button2"
16. runat="server" Font-Bold="True" ForeColor="Blue" Text="Click Here"/>
The elements can wrap, but the beginning of Button2 must immediately follow the end
of Button1 (the />character).
17. Switch to Design view.
Notice that Button1 and Button2 are right next to each other without a space between them.
18. Switch to Source view
19. On the Edit menu, in the Advanced submenu, click Format Document.
The document is reformatted, but Button1 and Button2 remain on the same line. If the editor
separated the buttons, it would introduce a space during rendering. Therefore, the editor does
not change the formatting that you have created.
Working in Split View
You can see both the Design view and Source view windows at the same time by using Split view.
To view a page in Split view
 Switch to Split view by clicking Split, which is located at the lower left of the window. Notice that
theSource view window occupies the upper half of the screen, and the Design view window the
lower half. Notice also that the two views are synchronized. If you double-click an item in one
view to select it, the corresponding item in the other view is highlighted.
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 Studio 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.
 The 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 can examine the 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 using Document Outline
1. Switch to Source view.
2. On the View menu, click Document Outline.
3. In Document Outline, click Button4.
In the editor, the <Button4> control that you added in the preceding procedure is selected.
The tag navigator provides information about the currently selected tag and where it is in the page
hierarchy.
To navigate using tag navigator
1. Position the cursor in the Button element.
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 Classattribute.
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> tag.
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, clicking 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 by using the tag navigator
1. Using the tag navigator, select the <tr> tag that contains the Button4 control.
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 cursor 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, seeWalkthrough: Creating and Modifying a CSS File.
 By default, the editor creates markup that is compatible with the XHTML5 standard. The editor
converts all HTML tag names to lowercase, even if you type them in uppercase. The editor also
encloses attribute (property) values in double quotation marks. For more information,
see Walkthrough: Advanced HTML Editing in Visual Studio for Web Forms Pages.
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. To learn
more about the editing facilities in Visual Studio, consult the following resources.
 To learn about the additional capabilities of the HTML editor, including custom formatting
options, outlining, and HTML validation, see Walkthrough: Advanced HTML Editing in Visual
Studio for Web Forms Pages.
 To learn how to work with styles in cascading style sheets, see Walkthrough: Creating and
Modifying a CSS File.
Walkthrough: Basic Data Access
Using the SqlDataSource
Control in Web Pages
Other Versions
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.
A Visual Studio project with source code is available to accompany this topic: Download.
Prerequisites
In order to complete this walkthrough, you will need the following:
 Visual Studio or Visual Web Developer Express installed on your computer.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web
Developmentcollection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.
 Access to the SQL Server Northwind database. The simplest option is to use the file-based copy of
Northwind that is included in the code example download for this topic. As an alternative, you can
download and install a version of Northwind to run on an instance of SQL Server on your
computer or your local network. 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.
Creating the Web Site
If you have already created a Web site in Visual Studio or Visual Web Developer Express (for example, by
completingWalkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site
and go to the next section. Otherwise, create a new Web site and page by following these steps.
This walkthrough uses a Web site project. You could use a Web application project instead. For
information about the difference between these Web project types, see Web Application Projects versus
Web Site Projects in Visual Studio.
To create a file system Web site
1. Open Visual Studio or Visual Web Developer Express.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site.
4. In the Web location box, select File System, and then enter the name of the folder where you
want to keep the pages for your Web site.
For example, type the folder name C:WebSites.
5. Click OK.
Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master
page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client
script files), and for authentication (ASP.NET membership).
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 Default.aspx 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
clickContinue.
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:
o It is more secure than storing the connection string in the page.
o 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 walkthrough, 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:
o The wizard created and configured a SqlDataSource control (named SqlDataSource1),
which incorporates the connection and query information that you specified.
o 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 theConnectionString and SelectQuery properties.
Note
You can easily change the look of the GridView control. In Designview, right-click
the GridView control, and then click 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.
Walkthrough: Creating
Master/Detail Web Pages in
Visual Studio
Other Versions
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:
 Visual Studio or Visual Web Developer.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web
Developmentcollection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.
 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 or a later version of Windows,
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 project (for example, by following the steps in Walkthrough:
Creating a Basic Web Forms Page in Visual Studio or Walkthrough: Basic Data Access Using the
SqlDataSource Control 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.
This walkthrough uses a Web site project. You could use a Web application project instead. For
information about the difference between these Web project types, see Web Application Projects versus
Web Site Projects in Visual Studio.
To create a file system Web site
1. Open Visual Studio or Visual Web Developer.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site.
4. In the Web location box, select File System, and then enter the name of the folder where you
want to keep the pages for your Web site.
For example, type the folder name C:WebSites.
5. Click OK.
Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master
page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client
script files), and for authentication (ASP.NET membership).
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
Connectionsand 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:
o Enter or select the name of your SQL Server computer. For a server on your computer,
enter (local).
o Select Use SQL Server Authentication.
o Enter a user name and password.
o Select Save my password.
o 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
Formatdrop-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.
19. This specifies that the value of the CategoryName field will be displayed as the text of the item in
the drop-down list.
20. 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.
21. 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 DropDownListcontrol 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 theSelected Fields list.
8. In the Selected Fields list, choose Select, and then in the CommandField property grid, set
its SelectTextproperty 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 toCategoryID.
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 Sourcelist and then use the wizard to do the following:
o Click Database.
o Connect to the Northwind database (connection NorthwindConnectionString).
o 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
DataNavigateUrlFields CustomerID
This indicates that the hyperlink should get its value
from theCustomerID column
DataNavigateUrlFormatString DetailsOrders.aspx?custid={0}
This creates a link that is hard-coded to navigate to
the DetailsOrders.aspx page. The link also passes a
query string variable named custid whose value will
be filled using the column referenced in
the DataNavigateUrlFields 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 toReturn 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.
Walkthrough: Editing and
Inserting Data in Web Pages
with the DetailsView Web
Server Control
Other Versions
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.
A Visual Studio project with source code is available to accompany this topic: Download.
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 Studio or Visual Web Developer Express.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web
Developmentcollection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.
 Microsoft Data Access Components (MDAC) version 2.7 or later.
If you are using the Microsoft Windows XP or Windows Server 2003 operating systems or later,
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 Developer Center on the MSDN Web site.
 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
This walkthrough uses a Web site project. You could use a Web application project instead. For
information about the difference between these Web project types, see Web Application Projects versus
Web Site Projects in Visual Studio.
To create a new file system Web site
1. Open Visual Studio or Visual Web Developer Express.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site.
4. In the Web location box, select File System, and then enter the name of the folder where you
want to keep the pages for your Web site.
For example, type the folder name C:WebSites.
5. Click OK.
Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master
page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client
script files), and for authentication (ASP.NET membership).
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.
o If the Data source list does not display Microsoft SQL Server (SqlClient), click Change,
and in theChange Data Source dialog box, select Microsoft SQL Server.
o 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 Database 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 Installed Templates, click Visual C# or Visual Basic, and then select Web Form.
3. In the Name box, type EditEmployees.aspx.
4. Click Add.
The EditEmployees.aspx page opens in Source view.
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 Datagroup, 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:
o It is more secure than storing it in the page.
o 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 theName box, click Employees.
8. Under Columns, select the EmployeeID, LastName, FirstName, and HireDate check boxes, and
then clickNext.
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 GridViewcontrol 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. Later 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 theChoose 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 procedure 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 validate user input to make sure input does not include
script or HTML elements. 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.
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.
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net
Walkthrough asp.net

More Related Content

What's hot

Dreamweaver cs6 step by step
Dreamweaver cs6 step by stepDreamweaver cs6 step by step
Dreamweaver cs6 step by stepzoran Jelinek
 
Joomla Quick Start 1
Joomla  Quick  Start 1Joomla  Quick  Start 1
Joomla Quick Start 1guest38bfe1
 
Start a Blog: Module 6
Start a Blog: Module 6Start a Blog: Module 6
Start a Blog: Module 6Merri Dennis
 
How to Use Dreamweaver cs6
How to Use Dreamweaver cs6 How to Use Dreamweaver cs6
How to Use Dreamweaver cs6 Salman Memon
 
Joomla Template Tutorial
Joomla Template TutorialJoomla Template Tutorial
Joomla Template Tutorialbrighteyes
 
Using Stylesheets To Design A Web Site In Dreamweaver Mx 2004
Using Stylesheets To Design A Web Site In Dreamweaver Mx 2004Using Stylesheets To Design A Web Site In Dreamweaver Mx 2004
Using Stylesheets To Design A Web Site In Dreamweaver Mx 2004brighteyes
 
Unit a adobe dreamweaver cs6
Unit a adobe dreamweaver cs6Unit a adobe dreamweaver cs6
Unit a adobe dreamweaver cs6Krista Lawrence
 
Illustrated introductory DreamWeaver
Illustrated introductory DreamWeaverIllustrated introductory DreamWeaver
Illustrated introductory DreamWeaverAshish Srivastava
 
Getting Started with Iron Speed Designer
Getting Started with Iron Speed DesignerGetting Started with Iron Speed Designer
Getting Started with Iron Speed DesignerIron Speed
 
An Introduction To Pbworks
An Introduction To PbworksAn Introduction To Pbworks
An Introduction To Pbworkschoikwokto
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD CombinationLotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD CombinationSean Burgess
 
INTRODUCTION TO VISUAL BASICS
INTRODUCTION TO VISUAL BASICS INTRODUCTION TO VISUAL BASICS
INTRODUCTION TO VISUAL BASICS Prof Ansari
 
Build your first rpa bot using IBM RPA automation
Build your first rpa bot using IBM RPA automationBuild your first rpa bot using IBM RPA automation
Build your first rpa bot using IBM RPA automationWinton Winton
 

What's hot (20)

Dreamweaver
DreamweaverDreamweaver
Dreamweaver
 
Dreamweaver cs6 step by step
Dreamweaver cs6 step by stepDreamweaver cs6 step by step
Dreamweaver cs6 step by step
 
Joomla Quick Start 1
Joomla  Quick  Start 1Joomla  Quick  Start 1
Joomla Quick Start 1
 
Start a Blog: Module 6
Start a Blog: Module 6Start a Blog: Module 6
Start a Blog: Module 6
 
How to Use Dreamweaver cs6
How to Use Dreamweaver cs6 How to Use Dreamweaver cs6
How to Use Dreamweaver cs6
 
Joomla Template Tutorial
Joomla Template TutorialJoomla Template Tutorial
Joomla Template Tutorial
 
Using Stylesheets To Design A Web Site In Dreamweaver Mx 2004
Using Stylesheets To Design A Web Site In Dreamweaver Mx 2004Using Stylesheets To Design A Web Site In Dreamweaver Mx 2004
Using Stylesheets To Design A Web Site In Dreamweaver Mx 2004
 
Oracle EMC 12C Grand Tour
Oracle EMC 12C Grand TourOracle EMC 12C Grand Tour
Oracle EMC 12C Grand Tour
 
Unit a adobe dreamweaver cs6
Unit a adobe dreamweaver cs6Unit a adobe dreamweaver cs6
Unit a adobe dreamweaver cs6
 
Illustrated introductory DreamWeaver
Illustrated introductory DreamWeaverIllustrated introductory DreamWeaver
Illustrated introductory DreamWeaver
 
Dreaweaver cs5
Dreaweaver cs5Dreaweaver cs5
Dreaweaver cs5
 
Getting Started with Iron Speed Designer
Getting Started with Iron Speed DesignerGetting Started with Iron Speed Designer
Getting Started with Iron Speed Designer
 
Fewd week7 slides
Fewd week7 slidesFewd week7 slides
Fewd week7 slides
 
An Introduction To Pbworks
An Introduction To PbworksAn Introduction To Pbworks
An Introduction To Pbworks
 
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD CombinationLotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
Lotusphere 2012 Speedgeeking - jQuery & Domino, a RAD Combination
 
Dreamweawer
DreamweawerDreamweawer
Dreamweawer
 
Fewd week8 slides
Fewd week8 slidesFewd week8 slides
Fewd week8 slides
 
INTRODUCTION TO VISUAL BASICS
INTRODUCTION TO VISUAL BASICS INTRODUCTION TO VISUAL BASICS
INTRODUCTION TO VISUAL BASICS
 
Understanding IDEs
Understanding IDEsUnderstanding IDEs
Understanding IDEs
 
Build your first rpa bot using IBM RPA automation
Build your first rpa bot using IBM RPA automationBuild your first rpa bot using IBM RPA automation
Build your first rpa bot using IBM RPA automation
 

Viewers also liked (13)

Android examples
Android examplesAndroid examples
Android examples
 
Sq lite manager
Sq lite managerSq lite manager
Sq lite manager
 
Cdn
CdnCdn
Cdn
 
00016335
0001633500016335
00016335
 
Tutorial 1
Tutorial 1Tutorial 1
Tutorial 1
 
Schemas and soap_prt
Schemas and soap_prtSchemas and soap_prt
Schemas and soap_prt
 
Cdn tutorial adcom
Cdn tutorial adcomCdn tutorial adcom
Cdn tutorial adcom
 
Jaxrs 1.0-final-spec
Jaxrs 1.0-final-specJaxrs 1.0-final-spec
Jaxrs 1.0-final-spec
 
Dynamically define rad grid using code behind in c# grid - ui for asp
Dynamically define rad grid using code behind in c#   grid - ui for aspDynamically define rad grid using code behind in c#   grid - ui for asp
Dynamically define rad grid using code behind in c# grid - ui for asp
 
sample tutorial
 sample tutorial  sample tutorial
sample tutorial
 
Create link button in radgrid dynamically without item template tags in aspx ...
Create link button in radgrid dynamically without item template tags in aspx ...Create link button in radgrid dynamically without item template tags in aspx ...
Create link button in radgrid dynamically without item template tags in aspx ...
 
Radgrid
RadgridRadgrid
Radgrid
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 

Similar to Walkthrough asp.net

BP304 - Blog It Up, Baby! Extending the new IBM Lotus Domino Blog Template
BP304 - Blog It Up, Baby! Extending the new IBM Lotus Domino Blog TemplateBP304 - Blog It Up, Baby! Extending the new IBM Lotus Domino Blog Template
BP304 - Blog It Up, Baby! Extending the new IBM Lotus Domino Blog TemplateSean Burgess
 
pracc III for presentation.pptx
pracc III for presentation.pptxpracc III for presentation.pptx
pracc III for presentation.pptxHailsh
 
pracc III for presentation.pptx
pracc III for presentation.pptxpracc III for presentation.pptx
pracc III for presentation.pptxHailsh
 
09 asp.net session13
09 asp.net session1309 asp.net session13
09 asp.net session13Vivek chan
 
Just Enough Web Design.doc.doc
Just Enough Web Design.doc.docJust Enough Web Design.doc.doc
Just Enough Web Design.doc.docbutest
 
3) web development
3) web development3) web development
3) web developmenttechbed
 
TID Chapter 8 Web Page Development
TID Chapter 8 Web Page DevelopmentTID Chapter 8 Web Page Development
TID Chapter 8 Web Page DevelopmentWanBK Leo
 
Getting Started with Dreamweaver
Getting Started with DreamweaverGetting Started with Dreamweaver
Getting Started with DreamweaverFrank Fucile
 
Share Point For Beginners V1
Share Point For Beginners V1Share Point For Beginners V1
Share Point For Beginners V1MJ Ferdous
 
SharePoint Publishing 101
SharePoint Publishing 101SharePoint Publishing 101
SharePoint Publishing 101Becky Bertram
 
Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web MahmoudOHassouna
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!rommel_gagasa
 

Similar to Walkthrough asp.net (20)

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
 
BP304 - Blog It Up, Baby! Extending the new IBM Lotus Domino Blog Template
BP304 - Blog It Up, Baby! Extending the new IBM Lotus Domino Blog TemplateBP304 - Blog It Up, Baby! Extending the new IBM Lotus Domino Blog Template
BP304 - Blog It Up, Baby! Extending the new IBM Lotus Domino Blog Template
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
 
pracc III for presentation.pptx
pracc III for presentation.pptxpracc III for presentation.pptx
pracc III for presentation.pptx
 
pracc III for presentation.pptx
pracc III for presentation.pptxpracc III for presentation.pptx
pracc III for presentation.pptx
 
09 asp.net session13
09 asp.net session1309 asp.net session13
09 asp.net session13
 
Just Enough Web Design.doc.doc
Just Enough Web Design.doc.docJust Enough Web Design.doc.doc
Just Enough Web Design.doc.doc
 
3) web development
3) web development3) web development
3) web development
 
As pnet
As pnetAs pnet
As pnet
 
TID Chapter 8 Web Page Development
TID Chapter 8 Web Page DevelopmentTID Chapter 8 Web Page Development
TID Chapter 8 Web Page Development
 
Dw cs3-introduction
Dw cs3-introductionDw cs3-introduction
Dw cs3-introduction
 
Getting Started with Dreamweaver
Getting Started with DreamweaverGetting Started with Dreamweaver
Getting Started with Dreamweaver
 
A comprehensive software infrastructure of .Net
A comprehensive software infrastructure of .Net  A comprehensive software infrastructure of .Net
A comprehensive software infrastructure of .Net
 
Share Point For Beginners V1
Share Point For Beginners V1Share Point For Beginners V1
Share Point For Beginners V1
 
SharePoint Publishing 101
SharePoint Publishing 101SharePoint Publishing 101
SharePoint Publishing 101
 
Web development
Web developmentWeb development
Web development
 
Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web
 
Asp notes
Asp notesAsp notes
Asp notes
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 

Recently uploaded

Thomas Calculus 12th Edition Textbook and helping material
Thomas Calculus 12th Edition Textbook and helping materialThomas Calculus 12th Edition Textbook and helping material
Thomas Calculus 12th Edition Textbook and helping materialsafdarhussainbhutta4
 
Abanoub Ghobrial, Planning Team Leader.pdf
Abanoub Ghobrial, Planning Team Leader.pdfAbanoub Ghobrial, Planning Team Leader.pdf
Abanoub Ghobrial, Planning Team Leader.pdfAbanoubGhobrial1
 
LinkedIn Strategic Guidelines April 2024
LinkedIn Strategic Guidelines April 2024LinkedIn Strategic Guidelines April 2024
LinkedIn Strategic Guidelines April 2024Bruce Bennett
 
What is the career path of a VFX artist?
What is the career path of a VFX artist?What is the career path of a VFX artist?
What is the career path of a VFX artist?santoshjadhav126
 
How to prepare yourself for a job interview.pptx
How to prepare yourself for a job interview.pptxHow to prepare yourself for a job interview.pptx
How to prepare yourself for a job interview.pptxJohnreyFalsarioBasid
 
Chapter 4 - Promoting Inclusive Culture.ppt
Chapter 4 - Promoting   Inclusive Culture.pptChapter 4 - Promoting   Inclusive Culture.ppt
Chapter 4 - Promoting Inclusive Culture.pptmoytopo
 
Abanoub Ghobrial, Planning Team Leader.pdf
Abanoub Ghobrial, Planning Team Leader.pdfAbanoub Ghobrial, Planning Team Leader.pdf
Abanoub Ghobrial, Planning Team Leader.pdfAbanoubGhobrial1
 
Get to know about Raquel Thompson Barbados.pdf
Get to know about Raquel Thompson Barbados.pdfGet to know about Raquel Thompson Barbados.pdf
Get to know about Raquel Thompson Barbados.pdfRaquel Thompson Barbados
 
Design, Desire and Demand Presentation.pptx
Design, Desire and Demand Presentation.pptxDesign, Desire and Demand Presentation.pptx
Design, Desire and Demand Presentation.pptxaaronbasko1
 
Network to Success - Using Social Media in Job Search
Network to Success - Using Social Media in Job SearchNetwork to Success - Using Social Media in Job Search
Network to Success - Using Social Media in Job SearchBruce Bennett
 
Transportation and Trade Part 5 (1) (1).pptx
Transportation and Trade Part 5 (1) (1).pptxTransportation and Trade Part 5 (1) (1).pptx
Transportation and Trade Part 5 (1) (1).pptxSheldon Byron
 
Nathan_Baughman_Resume_copywriter_and_editor
Nathan_Baughman_Resume_copywriter_and_editorNathan_Baughman_Resume_copywriter_and_editor
Nathan_Baughman_Resume_copywriter_and_editorNathanBaughman3
 
Training for Deaconess, biblical qualifications.ppt
Training for Deaconess, biblical qualifications.pptTraining for Deaconess, biblical qualifications.ppt
Training for Deaconess, biblical qualifications.pptVidalMendoza5
 
401799841-Increasing-Crimes-and-Suicides-Among-Youth.pptx
401799841-Increasing-Crimes-and-Suicides-Among-Youth.pptx401799841-Increasing-Crimes-and-Suicides-Among-Youth.pptx
401799841-Increasing-Crimes-and-Suicides-Among-Youth.pptxwaghmare9860lavin
 
APSC Motor Vechile Inspector 18 Posts.pdf
APSC Motor Vechile Inspector 18 Posts.pdfAPSC Motor Vechile Inspector 18 Posts.pdf
APSC Motor Vechile Inspector 18 Posts.pdfsoumita869
 
Career-Orientation-for-Grade-9-and-10.pptx
Career-Orientation-for-Grade-9-and-10.pptxCareer-Orientation-for-Grade-9-and-10.pptx
Career-Orientation-for-Grade-9-and-10.pptxGachaFluffy
 
Spanish Classes Online In India With Tutor At Affordable Price
Spanish Classes Online In India With Tutor At Affordable PriceSpanish Classes Online In India With Tutor At Affordable Price
Spanish Classes Online In India With Tutor At Affordable PriceFluent Fast Academy
 
Senior IT Professional with Master’s Degree with 21+ years of experience is...
Senior IT Professional with Master’s Degree with 21+ years of experience   is...Senior IT Professional with Master’s Degree with 21+ years of experience   is...
Senior IT Professional with Master’s Degree with 21+ years of experience is...Anas Acharath Parakat
 
Complete Benefits of career counseling in India
Complete Benefits of career counseling in IndiaComplete Benefits of career counseling in India
Complete Benefits of career counseling in IndiaMere Mentor
 
美国SU学位证,雪城大学毕业证书1:1制作
美国SU学位证,雪城大学毕业证书1:1制作美国SU学位证,雪城大学毕业证书1:1制作
美国SU学位证,雪城大学毕业证书1:1制作ss846v0c
 

Recently uploaded (20)

Thomas Calculus 12th Edition Textbook and helping material
Thomas Calculus 12th Edition Textbook and helping materialThomas Calculus 12th Edition Textbook and helping material
Thomas Calculus 12th Edition Textbook and helping material
 
Abanoub Ghobrial, Planning Team Leader.pdf
Abanoub Ghobrial, Planning Team Leader.pdfAbanoub Ghobrial, Planning Team Leader.pdf
Abanoub Ghobrial, Planning Team Leader.pdf
 
LinkedIn Strategic Guidelines April 2024
LinkedIn Strategic Guidelines April 2024LinkedIn Strategic Guidelines April 2024
LinkedIn Strategic Guidelines April 2024
 
What is the career path of a VFX artist?
What is the career path of a VFX artist?What is the career path of a VFX artist?
What is the career path of a VFX artist?
 
How to prepare yourself for a job interview.pptx
How to prepare yourself for a job interview.pptxHow to prepare yourself for a job interview.pptx
How to prepare yourself for a job interview.pptx
 
Chapter 4 - Promoting Inclusive Culture.ppt
Chapter 4 - Promoting   Inclusive Culture.pptChapter 4 - Promoting   Inclusive Culture.ppt
Chapter 4 - Promoting Inclusive Culture.ppt
 
Abanoub Ghobrial, Planning Team Leader.pdf
Abanoub Ghobrial, Planning Team Leader.pdfAbanoub Ghobrial, Planning Team Leader.pdf
Abanoub Ghobrial, Planning Team Leader.pdf
 
Get to know about Raquel Thompson Barbados.pdf
Get to know about Raquel Thompson Barbados.pdfGet to know about Raquel Thompson Barbados.pdf
Get to know about Raquel Thompson Barbados.pdf
 
Design, Desire and Demand Presentation.pptx
Design, Desire and Demand Presentation.pptxDesign, Desire and Demand Presentation.pptx
Design, Desire and Demand Presentation.pptx
 
Network to Success - Using Social Media in Job Search
Network to Success - Using Social Media in Job SearchNetwork to Success - Using Social Media in Job Search
Network to Success - Using Social Media in Job Search
 
Transportation and Trade Part 5 (1) (1).pptx
Transportation and Trade Part 5 (1) (1).pptxTransportation and Trade Part 5 (1) (1).pptx
Transportation and Trade Part 5 (1) (1).pptx
 
Nathan_Baughman_Resume_copywriter_and_editor
Nathan_Baughman_Resume_copywriter_and_editorNathan_Baughman_Resume_copywriter_and_editor
Nathan_Baughman_Resume_copywriter_and_editor
 
Training for Deaconess, biblical qualifications.ppt
Training for Deaconess, biblical qualifications.pptTraining for Deaconess, biblical qualifications.ppt
Training for Deaconess, biblical qualifications.ppt
 
401799841-Increasing-Crimes-and-Suicides-Among-Youth.pptx
401799841-Increasing-Crimes-and-Suicides-Among-Youth.pptx401799841-Increasing-Crimes-and-Suicides-Among-Youth.pptx
401799841-Increasing-Crimes-and-Suicides-Among-Youth.pptx
 
APSC Motor Vechile Inspector 18 Posts.pdf
APSC Motor Vechile Inspector 18 Posts.pdfAPSC Motor Vechile Inspector 18 Posts.pdf
APSC Motor Vechile Inspector 18 Posts.pdf
 
Career-Orientation-for-Grade-9-and-10.pptx
Career-Orientation-for-Grade-9-and-10.pptxCareer-Orientation-for-Grade-9-and-10.pptx
Career-Orientation-for-Grade-9-and-10.pptx
 
Spanish Classes Online In India With Tutor At Affordable Price
Spanish Classes Online In India With Tutor At Affordable PriceSpanish Classes Online In India With Tutor At Affordable Price
Spanish Classes Online In India With Tutor At Affordable Price
 
Senior IT Professional with Master’s Degree with 21+ years of experience is...
Senior IT Professional with Master’s Degree with 21+ years of experience   is...Senior IT Professional with Master’s Degree with 21+ years of experience   is...
Senior IT Professional with Master’s Degree with 21+ years of experience is...
 
Complete Benefits of career counseling in India
Complete Benefits of career counseling in IndiaComplete Benefits of career counseling in India
Complete Benefits of career counseling in India
 
美国SU学位证,雪城大学毕业证书1:1制作
美国SU学位证,雪城大学毕业证书1:1制作美国SU学位证,雪城大学毕业证书1:1制作
美国SU学位证,雪城大学毕业证书1:1制作
 

Walkthrough asp.net

  • 1. Walkthrough: Creating a Basic Web Forms Page in Visual Studio Other Versions This walkthrough provides you with an introduction to the Web development environment in Visual Studio and in Visual Web Developer Express for ASP.NET Web Forms pages. This walkthrough guides you through creating a simple ASP.NET Web Forms page and illustrates the basic techniques of creating a new page, adding controls, and writing code. Note This topic applies only to ASP.NET Web Forms pages. It does not apply to pages that you create using ASP.NET MVC (Model View Controller) or ASP.NET Web Pages. Tasks illustrated in this walkthrough include:  Creating a file system Web site project.  Familiarizing yourself with Visual Studio.  Creating a single-file ASP.NET Web Forms page.  Adding controls.  Adding event handlers.  Running pages by using the Web server that is built into Visual Studio for testing. Prerequisites In order to complete this walkthrough, you will need:  Visual Studio or Visual Web Developer Express. For download information, see the Visual Studio Development Center Web site. Note If you are using Visual Studio, this walkthrough assumes that you selected the Web Developmentcollection of settings the first time that you started Visual Studio. For more
  • 2. information, see How to: Select Web Development Environment Settings.  The .NET Framework, which is installed when you install Visual Studio or Visual Web Developer Express. Creating a Web Site Project and a Web Forms Page In this part of the walkthrough, you will create a Web site project 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 project 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 project is one that stores pages and other files in a folder that you choose somewhere on your computer. Other Web project options include the following:  A local IIS Web site project, which stores your files in a subfolder of the local IIS root (typically, inetpubwwwroot).  An FTP site project, which stores files on a remote server that you gain access to across the Internet by using File Transfer Protocol (FTP).  A remote IIS Web site project, which stores files on a remote server that you can access across a local network.  A Web application project, which is similar to a file system Web site project except you compile it before deployment and deploy it as a dynamic link library (.dll) file. For more information about the difference between Web site projects and Web application projects, see Web Application Projects versus Web Site Projects in Visual Studio. To create a file system Web site 1. Open Visual Studio or Microsoft Visual Web Developer Express. 2. On the File menu, click New Web Site. The New Web Site dialog box appears, as shown in the following illustration:
  • 3. 3. Under Installed Templates, click Visual Basic or C# and then select ASP.NET Web Site. When you create a Web site project, you specify a template. Each template creates a Web project that contains different files and folders. In this walkthrough, you are creating a Web site based on the ASP.NET Web Sitetemplate, which creates files and folders that are typically used in ASP.NET Web sites. 4. In the Web 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:BasicWebSite. 5. Click OK. Visual Studio creates a Web project that includes prebuilt functionality for layout (a master page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script files), and for authentication (ASP.NET membership). When a new page is created, by default Visual Studio displays the page in Source view, where you can see the page's HTML elements. The following illustration shows what you would see in Source view if you created a new Web page named FirstWebPage.aspx. A Tour of the Visual Studio Web Development Environment Before you proceed with working on the page, it is useful to familiarize yourself with the Visual Studio development environment. The following illustration shows you the windows and tools that are available in Visual Studio and Microsoft Visual Web Developer Express.
  • 4. Note This diagram shows default windows and window locations. The View menu allows you to display additional windows, and to rearrange and resize windows to suit your preferences. If changes have already been made to the window arrangement, what you see will not match the illustration. The Visual Studio environment To familiarize yourself with the Web designer  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.) o Toolbars. Provide commands for formatting text, finding text, and so on. Some toolbars are available only when you are working in Design view. o Solution Explorer window. Displays the files and folders in your Web site. o Document window. Displays the documents you are working on in tabbed windows. You can switch between documents by clicking tabs. o Properties window. Allows you to change settings for the page, HTML elements, controls, and other objects. o 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. Split view displays both the Designview and the Source view for the document. You will work with the Design and Source 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. o ToolBox. Provides controls and HTML elements that you can drag onto your page. Toolboxelements are grouped by common function.
  • 5. o Server Explorer/Database Explorer. Displays database connections. If Server Explorer is not visible, on the View menu, click Server Explorer or Database Explorer. Note The Server Explorer window is named Database Explorer in Microsoft Visual Web Developer Express. To see all available menu items in Microsoft Visual Web Developer Express, on the Toolsmenu, click Settings, and then click Expert Settings. Creating a New ASP.NET Web Forms Page When you create a new Web site using the ASP.NET Web Site project template, Visual Studio adds an ASP.NET 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 that displays the file name and then click Close. 2. In Solution Explorer, right-click the Web site (for example, C:BasicWebSite), and then click Add New Item. The Add New Item dialog box is displayed. The following illustration shows an example of the Add New Item dialog box. 3. In the template list, select Web Form. 4. In the Name box, type FirstWebPage.
  • 6. When you created the Web site project, you specified a default language based on the project template that you selected. However, each time you create a new page or component for your Web site, you can select the programming language for that page or component. You can use different programming languages in the same Web site. 5. Clear the Place code in separate file check box. In this walkthrough, you are creating a single-file Web Forms page with the code and HTML in the same page. The code for ASP.NET Web Forms pages can be located either in the page or in a separate class file. 6. Click Add. Visual Studio creates the new page and opens it. Adding HTML to the Web Forms 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 except for a dashed line that outlines a rectangle. This rectangle represents a div element on the page. 2. Click inside the rectangle that is outlined by a dashed line. 3. Type Welcome to Visual Web Developer and press ENTER twice. The following illustration shows the text you typed in Design view. 4. Switch to Source view. You can see the HTML that you created by typing in Design view, as shown in the following illustration.
  • 7. 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 Visual Studio Development Server, which runs locally and does not require IIS. For file system Web site projects, the default Web server in Visual Studio and Microsoft Visual Web Developer Express is the Visual Studio Development Server. To run the page 1. In Solution Explorer, right-click FirstWebPage.aspx and select Set as Start Page. 2. Press CTRL+F5 to run the page. Visual Studio starts the Visual Studio Development Server. An icon appears in the Windows taskbar to indicate that the Visual Studio Development Server is running, as shown in the following illustration. The page is displayed in the browser. Although the page you created has a file-name extension of .aspx, it currently runs like any HTML page. To display a page in the browser you can also right-click the page in Solution Explorer and select View in Browser. 3. Close the browser.
  • 8. Adding and Programming Controls 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 Forms pages. However, you can program the controls with code that runs on the server, not the client. You will add a Button control, a TextBox control, and a Label control to the page and write code to handle the Clickevent for the Button control. To add controls to the page 1. Click the Design tab to switch to Design view. 2. Put the insertion point at the end of the Welcome to Visual Web Developer text and press ENTER five or more times to make some room in the div element box. 3. In the Toolbox, expand the Standard group. 4. Drag a TextBox control onto the page and drop it in the middle of the div element box that has Welcome to Visual Web Developer in the first line. 5. Drag a Button control onto the page and drop it to the right of the TextBox control. 6. Drag a Label control onto the page and drop it on a separate line below the Button control. 7. 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 illustration shows how the three controls appear in Design view. Setting Control Properties Visual Studio 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. The text you entered appears on the button in the designer, as shown in the following illustration.
  • 9. Note If the Properties window is not displayed, press F4 to display it. 2. 3. Switch to Source view. Source view displays the HTML for the page, including the elements that Visual Studio 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 Buttoncontrol, 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". Therunat="server" attribute and the asp: prefix for control tags mark the controls so that they are processed by ASP.NET on the server when the page runs. Code outside of <form runat="server"> and <script runat="server"> elements is sent unchanged to the browser, which is why the ASP.NET code must be inside an element whose opening tag contains the runat="server" attribute. 4. Put the insertion point after asp:Label in 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 illustration shows the IntelliSense drop-down list for the Labelcontrol.
  • 10. 5. Select ForeColor and then type an equal sign and a quotation mark (="). IntelliSense displays a list of colors. Note You can display an IntelliSense drop-down list at any time by pressing CTRL+J. 6. Select a color for the Label control's text. Make sure you select a color that is dark enough to read against a white background. The ForeColor attribute is completed with the color that you have selected, including the closing quotation mark. 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 Studio switches to Source view and creates a skeleton event handler for the Button control's default event, the Click event.
  • 11. Note Double-clicking a control in Designview is just one of several ways you can create event handlers. 3. Inside the handler, type Label1 followed by a period (.). When you type the period after Label, Visual Studio displays a list of available members for the Labelcontrol, as shown in the following illustration. 4. Finish the Click event handler for the button so that it reads as shown in the following code example. C# VB protected void Button1_Click(object sender, System.EventArgs e) { Label1.Text = TextBox1.Text + ", welcome to Visual Studio!"; }
  • 12. 5. Scroll down to the <asp:Button> element. Note that the <asp:Button> element now has the attributeonclick="Button1_Click". This attribute binds the button's Click event to the handler method you coded in the previous step. Event handler methods can have any name; the name you see is the default name created by Visual Studio. The important point is that the name used for the onclick attribute must match the name of a method in the page. 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 Visual Studio 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 Buttoncontrol'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 <input type="submit"> element. 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. TheCalendar 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 System.Web.UI.WebControls.Calendar control to the page and format it. To add a Calendar control 1. In Visual Studio, switch to Design view. 2. From the Standard section of the Toolbox, drag a Calendar control onto the page and drop it below the divelement that contains the other controls: 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 illustration shows the Calendar control as rendered in Design view.
  • 13. 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 illustration shows the Auto Format dialog box for the Calendar control.
  • 14. 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 illustration shows the Calendar control in Source view. (The exact markup that you see in Source view might differ slightly from the illustration.)
  • 15. 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. In Design view, double-click the Calendar control. A new event handler is created in Source view. 2. Finish the SelectionChanged event handler with the following highlighted code. C# VB protected void Calendar1_SelectionChanged(object sender, System.EventArgs e) { Label1.Text = Calendar1.SelectedDate.ToLongDateString(); } 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.
  • 16. 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. Visual Studio Templates for Web Projects .NET Framework 4.5 Visual Studio includes project templates to help you get started when you create a web project. You can create web application projects or web site projects. By considering the most appropriate project type before you begin, you can save time when you create, test, and deploy the web project. Web Project Templates From the File menu, you can select either New Project or New Web Site. The New Project dialog box provides a list of web application templates. Use the web application project template to create web applications that are compiled into an assembly and that provide rich options for deployment. The New Web Site dialog box provides a list of web site templates. Use the Web Site project template when you want to compile the source code dynamically. For more information about the differences between web project types, see Web Application Projects versus Web Site Projects. Note You can install additional products by using the NuGet package manager. In some cases, these products include additional templates for new projects. The lists in this topic show you only the templates that are included by default with Visual Studio 2012. Web Application Templates Web application templates help you create a web project that is compiled into an assembly for deployment. The following table lists templates that appear in the New Project dialog box under the Web category after you select a language (Visual Basic or Visual C#). Project Template More Information ASP.NET Web Forms Application Use this project template to create a web application that is based on ASP.NET Web Forms pages and that includes the following functionality. You can choose not to use any of these features when they are not required for your application.  A master page.  A cascading style sheet.  Login security that uses the ASP.NET membership system.
  • 17.  Ajax scripting that uses jQuery.  Navigation that uses a menu control. By default, the ASP.NET Web Application project template includes the following:  Folders to contain membership pages, client script files, and cascading style sheet files.  A data folder (App_Data), which is granted permissions that allow ASP.NET to read and write to it at run time.  A master page (the Site.master file).  Web pages named Default.aspx, Contact.aspx, and About.aspx. These content pages are based on the default master.  A global application class (Global.asax file).  A Web.config file.  A Packages.config file.  For more information, see ASP.NET Web Application Projects and Web Application Projects versus Web Site Projects in Visual Studio. ASP.NET MVC 3 Web Application Use this project template to create web applications that use a model-view- controller pattern, using the ASP.NET MVC 3 release. The MVC pattern helps separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. In addition, this project template promotes test-driven development (TDD). For more information, see ASP.NET MVC Overview. ASP.NET MVC 4 Web Application Use this project template to create web applications that use a model-view- controller pattern, using the ASP.NET MVC 4 release. For more information, see ASP.NET MVC Overview. ASP.NET Empty Web Application This template creates an ASP.NET web application that includes a Web.config file, but no other files. Use this project template when you do not require the functionality built into the standard template. ASP.NET Dynamic Data Entities Web Application Use this project template to create a Dynamic Data web application that uses the ADO.NET Entity Framework. This type of Dynamic Data web application can target any relational database. Dynamic Data automatically generates a functional web application for viewing and editing data, based on the schema of the data. For more information, see ASP.NET Dynamic Data Overview. ASP.NET AJAX Server Control Use this project template to create a web server control for ASP.NET Web Forms pages that incorporates Ajax functionality. The control consists of
  • 18. server and client code that work together to produce rich client behavior. For more information, see ASP.NET AJAX Overview. ASP.NET AJAX Server Control Extender Use this project template to create an Ajax component that enhances the client capabilities of standard ASP.NET web server controls. For more information, see ASP.NET AJAX Extender Controls Overview. ASP.NET Server Control Use this project template to create a custom ASP.NET web server control that can be used in ASP.NET Web Forms pages. For more information, see Developing Custom ASP.NET Server Controls. Web Site Templates Web site templates help you create a web project that by default is compiled dynamically. The following table lists templates that appear in the New Web Site dialog box. Project Template More Information ASP.NET Web Forms Site Use this project template to create a website that includes the following functionality. You can choose not to use any of these features when they are not required for your application.  A master page.  A cascading style sheet.  Login security that uses the ASP.NET membership system.  Ajax scripting that uses jQuery.  Navigation using a menu control. By default, the ASP.NET Web Site project template includes the following:  Folders to contain membership pages, client script files, and cascading style sheet files.  A data folder (App_Data), which is granted permissions that allow ASP.NET to read and write to it at run time.  A master page (.master file).  Web pages named Default.aspx and About.aspx. In the project template, these pages are content pages that use default master page.  A global application class (Global.asax file).  A Web.config file. For more information, see Walkthrough: Creating a Basic Web Page in Visual Studio. ASP.NET Web Site (Razor v2) Use this project template to create a website that uses ASP.NET Web Pages version 2 with Razor syntax. For more information, see Introduction to ASP.NET Web Programming Using the Razor Syntax. ASP.NET Web Site (Razor) Use this project template to create a website that uses ASP.NET Web Pages with the Razor syntax. For more information, see Introduction to ASP.NET
  • 19. Web Programming Using the Razor Syntax. ASP.NET Empty Web Site This template creates an ASP.NET website that includes a Web.config file but no other files. Use this project template when you do not require the functionality built into the standard. ASP.NET Dynamic Data Entities Web Site Use this project template to create a Dynamic Data website that uses the ADO.NET Entity Framework. This type of Dynamic Data web application can target any relational database. Dynamic Data automatically generates a functional web application for viewing and editing data, based on the schema of the data. For more information, see ASP.NET Dynamic Data. WCF Service Use this project template to create a Windows Communication Foundation (WCF) service. You can extend the service so that a website, web application, Silverlight application, Ajax application, or other client can call it. For more information, see Windows Communication Foundation. ASP.NET Reports Web Site Use this project template to create an ASP.NET website that contains a report (.rdlc file), a default ASP.NET Web Forms page (.aspx file) that contains a ReportViewer control, and a Web.config file. For more information, see Microsoft Reports. Walkthrough: Creating a Basic Web Forms Page with Code Separation in Visual Studio Other Versions When you create ASP.NET Web Forms pages and write code in them, you can select from two models for how to manage the visible elements (controls and 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
  • 20. "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 Forms pages that use code separation. Note This topic applies only to ASP.NET Web Forms pages. It does not apply to pages that you create using ASP.NET MVC (Model View Controller) or ASP.NET Web Pages. The single-file model is introduced in Walkthrough: Creating a Basic Web Forms Page in Visual Studio. 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 Studio 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. Tasks illustrated in this walkthrough include:  Creating an ASP.NET Web Forms page with code separation.  Adding server controls.  Adding event handlers.  Running pages with the Visual Studio Development Server. Prerequisites In order to complete this walkthrough, you will need:  Visual Studio or Visual Web Developer Express. Note If you are using Visual Studio, the walkthrough assumes that you selected the Web Developmentcollection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings. Creating a Web Site Project and Page In this part of the walkthrough, you will create a Web site project 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 Forms Web site project in Visual Studio (for example, by following the steps inWalkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and skip to "Creating a New Page" later in this walkthrough. Otherwise, create a new Web site project and page by following these steps. To create a file system Web site project 1. Open Visual Studio or Visual Web Developer Express. 2. In the File menu, click New Web Site.
  • 21. The New Web Site dialog box is displayed. 3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site. 4. In the Web location box, select File System, and then enter the name of the folder where you want to keep the pages for your Web site. For example, type the folder name C:WebSites. 5. Click OK. Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script files), and for authentication (ASP.NET membership). Creating a New Web Forms Page When you create a new Web site project, Visual Studio adds a Web Forms page named Default.aspx. By default, Visual Studio 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 then click Close. 2. In Solution Explorer, right-click the Web site (for example, C:BasicWebSite) and then click Add New Item. 3. Under Installed Templates, click Visual Basic or Visual C# and then select Web Form from the list. 4. In the Name box, enter WebPageSeparated. 5. Make sure that the Place code in separate file check box is selected. 6. Make sure that the Select master page check box is cleared. For this walkthrough, you will create a page that does not use the master page that is included in the Web site project. 7. Click Add. Visual Studio 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 Web Forms 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. Place the insertion pointer in the div element that is already on the page. 3. Type the words Welcome to Visual Studio Using Code Separation. 4. 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 Server Controls In this part of the walkthrough, you will add server controls to the Web Forms page: a button, text box, and label control. You will also write code to handle the button's Click event. Server controls, which
  • 22. include buttons, labels, text boxes, and other familiar controls, provide typical form-processing capabilities for your ASP.NET Web Forms 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. Place the insertion pointer after the text that you added previously. 3. Press ENTER a few times to make some room. 4. From the Standard tab in the Toolbox, drag three controls onto the page: a TextBox control, a Button control, and a Label control. 5. 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 Server Control Properties Visual Studio offers you various ways to set the properties of server 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 markup for the page, including the elements that Visual Studio has created for the server controls. Server controls are declared using HTML-like syntax, except that the tags use the prefix asp: and include the attribute runat="server". 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". Therunat="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 Studio 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. C# VB protected void Button1_Click(object sender, System.EventArgs e) { Label1.Text = TextBox1.Text + ", welcome to Visual Studio!"; }
  • 23. 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 Web Forms page named WebPageSeparated: 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. C# VB <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebPageSeparated.aspx.cs" Inherits="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 Web Forms page. The Inherits attribute identifies the class defined in the code-behind file from which the .aspx page is derived. By default, Visual Studio 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. 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 Visual Studio Development Server. 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.
  • 24. The page works exactly the same as it would if it were a single-file page. (If you followed the steps inWalkthrough: Creating a Basic Web Forms Page in Visual Studio 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 Forms 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 site projects using Microsoft Internet Information Services (IIS), and FTP, and you can work with Web application projects. For details, see Types of Web Site Projects in Visual Studioand Web Application Projects versus Web Site Projects in Visual Studio.  Add data access to Web Forms pages. For details, see Walkthrough: Basic Data Access Using the SqlDataSource Control 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. Walkthrough: Basic HTML Editing in Visual Studio for Web Forms Pages .NET Framework 4.5 Other Versions Microsoft Visual Studio 2012 provides a rich HTML editing experience for Web Forms pages. The Visual Studio HTML editor lets you work in WYSIWYG mode and also lets you work directly with HTML markup for finer control. This walkthrough introduces you to the HTML editing features of Visual Studio. Note This topic applies to ASP.NET Web Forms pages. You can use Source view for editing pages
  • 25. in ASP.NET MVC (Model View Controller)or ASP.NET Web Pages applications (.cshtml files), but Design view is fully supported only for Web Forms pages. Web server controls are used only in Web Forms pages. Tasks illustrated in this walkthrough include the following:  Creating and editing HTML in Design view.  Creating and editing HTML in Source view.  Using Split view.  Using navigation tools to move quickly through your HTML tags. Prerequisites In order to complete this walkthrough, you need the following:  Visual Studio or Visual Studio Express for Web installed on your computer. Note If you are using Visual Studio, the walkthrough assumes that you selected the Web Developmentcollection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings.  A general understanding of how to work in Visual Studio. For an introduction to how to create Web Forms pages in Visual Studio, see Walkthrough: Creating a Basic Web Forms Page in Visual Studio. Creating the Web Site and Web Forms Page If you have already created a Web Forms site in Visual Studio or Visual Studio Express for Web (for example, by completing Walkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that web site and go to the next section. Otherwise, create a website and Web Forms page by following these steps. Note This walkthrough uses a web site project. You could use a web application project instead. For information about the difference between these web project types, see Web Application Projects versus Web Site Projects. To create a file system website 1. Open Visual Studio or Visual Studio Express for Web. 2. In the File menu, click New Web Site. The New Web Site dialog box is displayed. 3. Under Installed, click Visual Basic or Visual C# and then select ASP.NET Empty Web Site. For this walkthrough, you create a website that does not include prebuilt pages and other resources.
  • 26. 4. In the Web location box, select File System, and then enter the name of the folder where you want to keep the pages for your website. For example, type the folder name C:WebSites. 5. Click OK. Visual Studio creates a website project that includes a Web.config file. 6. In Solution Explorer, right-click the root of your Web site, and then click Add New Item. 7. Select Web Form, name the file Default.aspx, and then click Add. 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 Web Forms 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 select it, and then on the Formatting toolbar click Heading 1. 4. Press ENTER after ASP.NET Web Page, and then type This page is powered by ASP.NET. 5. Highlight the text, then, on the Format menu, click New Style.
  • 27. The New Style dialog box appears. 6. Select the Apply new style to document selection option. 7. Select a font from the font-family drop-down list and then click Apply. The font family is applied to the selected text.
  • 28. 8. Under Category, click Block, and then select (value) from the line-height drop-down list. Enter a value for line height.
  • 29. 9. Select (value) from the letter-spacing dropdown list. Enter a value for letter spacing. Click Apply to see the values applied to the selected text. 10. Click OK. Viewing Tag Information When you are working in Design view, you might want to see tags such as div and span that do not have a visual rendering. To see HTML design surface tags in Design view  On the View menu, point to Visual Aids, and make sure that ASP.NET Non-visual Controls is selected. The designer displays symbols for paragraphs, line breaks, and other tags that do not render text. The symbols are not all shown at the same time, but when you click a visual element, the nonvisual element that precedes it is shown. 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 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. Put the cursor to the right of the text 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 and drop it in the space you created in the preceding step.
  • 30. Note You can also add a control by double-clicking it. 3. 4. Drag a Button control onto the page and drop it to the right of the TextBox control that you added in the preceding step. The TextBox and Button controls are ASP.NET web server controls, not HTML elements.
  • 31. 5. Put the cursor to the right of the Button control and then press ENTER. 6. On the Table menu, click Insert Table. The Insert Table dialog box appears.
  • 32. 7. 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.
  • 33. 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.
  • 34. 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 the Properties window. To set properties by using the Properties window 1. Select the Button control that you added in "Adding Controls and Elements" earlier in this walkthrough. 2. In Properties window, set Text to Click Here, and ForeColor to a different color.
  • 35. 3. Place the cursor in the ASP.NET hyperlink that you created in the preceding section. Notice that in the Properties window, the hreef 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 Studio starts IIS Express, which is a local web server that you can use to test pages without using a full IIS server. Note You can run pages in several ways. If you press CTRL+F5, Visual Studio 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 Designview. You can also run pages in the debugger. For more information, see Walkthrough: Debugging Web Pages in Visual Web Developer. Changing the Default View By default, Visual Studio opens new pages in Source view. To change the default page view to Design view 1. On the Tools menu, click Options 2. Make sure that the Show all settings options is selected at the bottom of the dialog box. 3. Open the HTML Designer node and then select General. Under Start Pages in, click Design view.
  • 36. 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 bottom 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 opening <asp:button> tag. 2. From the HTML group in the Toolbox (not the Standard group), drag a Table element onto the page and place it just above the </form> tag. The editor also helps you when you type markup manually. For example, the editor provides context- sensitive choices that finish 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. You can see the error or warning information by holding the mouse over the markup text. To edit HTML in Source view 1. Position the cursor 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.
  • 37. 2. Enter "a" to create an anchor tag, and then press the SPACEBAR. The editor displays a list of attributes that are appropriate for an anchor tag. Note The letter a (anchor element) might not appear as an option, depending on the validation target that is set for the site or the page. However, you can still create an anchor element by entering "a" without selecting an item in the drop-down list. Validation targets are discussed later in this topic.
  • 38. 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.
  • 39. 4. In the 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 by entering the text Home between the opening and closing tags. The element now resembles the following example: <a href="Default.aspx">Home</a> 6. Position the cursor 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. 7. 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. However, you can 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: 2. <asp:Button 3. id="Button1" 4. runat="server" 5. Font-Bold="True" 6. ForeColor="Blue" 7. Text="Click Here" />
  • 40. Notice that after you indent the first attribute, when you press ENTER in the tag, subsequent lines are indented to match. 8. Switch to Design view. 9. Right-click the Button control, and then click Copy. 10. Position the cursor below the Button control, right-click, and then click Paste. Visual Studio creates a button with the ID property set to Button2. 11. From the Standard group in the Toolbox, drag a third Button control onto the page, which creates a button named Button3. 12. Switch to Source view. Notice that Button2 is formatted exactly the way that you formatted Button1. On the other hand, Button3is formatted using the default formatting for Button controls. Note For more information on how to customize the formatting of individual elements, see Walkthrough: Advanced HTML Editing in Visual Studio for Web Forms Pages. 13. Edit the document so that Button1 and Button2 are on the same line without a space between them, as shown in the following example: 14. <asp:Button ID="Button1" runat="server" Font-Bold="True" 15. ForeColor="Blue" Text="Click Here" /><asp:Button ID="Button2" 16. runat="server" Font-Bold="True" ForeColor="Blue" Text="Click Here"/> The elements can wrap, but the beginning of Button2 must immediately follow the end of Button1 (the />character). 17. Switch to Design view. Notice that Button1 and Button2 are right next to each other without a space between them. 18. Switch to Source view 19. On the Edit menu, in the Advanced submenu, click Format Document. The document is reformatted, but Button1 and Button2 remain on the same line. If the editor separated the buttons, it would introduce a space during rendering. Therefore, the editor does not change the formatting that you have created. Working in Split View You can see both the Design view and Source view windows at the same time by using Split view. To view a page in Split view  Switch to Split view by clicking Split, which is located at the lower left of the window. Notice that theSource view window occupies the upper half of the screen, and the Design view window the lower half. Notice also that the two views are synchronized. If you double-click an item in one view to select it, the corresponding item in the other view is highlighted. 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 Studio 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.
  • 41.  The 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 can examine the 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 using Document Outline 1. Switch to Source view. 2. On the View menu, click Document Outline. 3. In Document Outline, click Button4. In the editor, the <Button4> control that you added in the preceding procedure is selected. The tag navigator provides information about the currently selected tag and where it is in the page hierarchy. To navigate using tag navigator 1. Position the cursor in the Button element.
  • 42. 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 Classattribute. 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.
  • 43. 3. In the tag navigator, click the <td> tag to the left of the selected <table> tag. 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, clicking 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 by using the tag navigator 1. Using the tag navigator, select the <tr> tag that contains the Button4 control. 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 cursor 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.
  • 44. 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, seeWalkthrough: Creating and Modifying a CSS File.  By default, the editor creates markup that is compatible with the XHTML5 standard. The editor converts all HTML tag names to lowercase, even if you type them in uppercase. The editor also encloses attribute (property) values in double quotation marks. For more information, see Walkthrough: Advanced HTML Editing in Visual Studio for Web Forms Pages. 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. To learn more about the editing facilities in Visual Studio, consult the following resources.  To learn about the additional capabilities of the HTML editor, including custom formatting options, outlining, and HTML validation, see Walkthrough: Advanced HTML Editing in Visual Studio for Web Forms Pages.  To learn how to work with styles in cascading style sheets, see Walkthrough: Creating and Modifying a CSS File. Walkthrough: Basic Data Access Using the SqlDataSource Control in Web Pages Other Versions 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.
  • 45.  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. A Visual Studio project with source code is available to accompany this topic: Download. Prerequisites In order to complete this walkthrough, you will need the following:  Visual Studio or Visual Web Developer Express installed on your computer. Note If you are using Visual Studio, the walkthrough assumes that you selected the Web Developmentcollection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings.  Access to the SQL Server Northwind database. The simplest option is to use the file-based copy of Northwind that is included in the code example download for this topic. As an alternative, you can download and install a version of Northwind to run on an instance of SQL Server on your computer or your local network. 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. Creating the Web Site If you have already created a Web site in Visual Studio or Visual Web Developer Express (for example, by completingWalkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and go to the next section. Otherwise, create a new Web site and page by following these steps. This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio. To create a file system Web site 1. Open Visual Studio or Visual Web Developer Express. 2. In the File menu, click New Web Site. The New Web Site dialog box is displayed. 3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site.
  • 46. 4. In the Web location box, select File System, and then enter the name of the folder where you want to keep the pages for your Web site. For example, type the folder name C:WebSites. 5. Click OK. Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script files), and for authentication (ASP.NET membership). 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 Default.aspx 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.
  • 47. 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.
  • 48. 7. Click New Connection. 8. In the Choose Data Source dialog box, under Data source, click Microsoft SQL Server, and then clickContinue. The Add Connection dialog box appears. 9. In the Server name box, enter the name of the SQL Server that you want to use.
  • 49. 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: o It is more secure than storing the connection string in the page. o 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.
  • 50. 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 walkthrough, 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: o The wizard created and configured a SqlDataSource control (named SqlDataSource1), which incorporates the connection and query information that you specified.
  • 51. o 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 theConnectionString and SelectQuery properties. Note You can easily change the look of the GridView control. In Designview, right-click the GridView control, and then click 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.
  • 52. 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.
  • 53. 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.
  • 54. Walkthrough: Creating Master/Detail Web Pages in Visual Studio Other Versions 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:  Visual Studio or Visual Web Developer. Note If you are using Visual Studio, the walkthrough assumes that you selected the Web Developmentcollection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings.  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.
  • 55.  Microsoft Data Access Components (MDAC) version 2.7 or later. If you are using Microsoft Windows XP or Windows Server 2003 or a later version of Windows, 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 project (for example, by following the steps in Walkthrough: Creating a Basic Web Forms Page in Visual Studio or Walkthrough: Basic Data Access Using the SqlDataSource Control 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. This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio. To create a file system Web site 1. Open Visual Studio or Visual Web Developer. 2. In the File menu, click New Web Site. The New Web Site dialog box is displayed. 3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site. 4. In the Web location box, select File System, and then enter the name of the folder where you want to keep the pages for your Web site. For example, type the folder name C:WebSites. 5. Click OK. Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script files), and for authentication (ASP.NET membership). 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 Connectionsand 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: o Enter or select the name of your SQL Server computer. For a server on your computer, enter (local). o Select Use SQL Server Authentication. o Enter a user name and password. o Select Save my password. o 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
  • 56. 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 Formatdrop-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
  • 57. If no items appear in the list, click the Refresh Schema link. 19. This specifies that the value of the CategoryName field will be displayed as the text of the item in the drop-down list. 20. 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. 21. 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 DropDownListcontrol you added earlier. 15. Click Add. 16. Click OK to close the Add WHERE Clause dialog box. 17. Click Next.
  • 58. 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 theSelected Fields list. 8. In the Selected Fields list, choose Select, and then in the CommandField property grid, set its SelectTextproperty 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 toCategoryID. 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.
  • 59. 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
  • 60. 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 Sourcelist and then use the wizard to do the following: o Click Database. o Connect to the Northwind database (connection NorthwindConnectionString). o 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 DataNavigateUrlFields CustomerID This indicates that the hyperlink should get its value from theCustomerID column DataNavigateUrlFormatString DetailsOrders.aspx?custid={0} This creates a link that is hard-coded to navigate to the DetailsOrders.aspx page. The link also passes a query string variable named custid whose value will be filled using the column referenced in the DataNavigateUrlFields 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.
  • 61. 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 toReturn 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. Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control Other Versions
  • 62. 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. A Visual Studio project with source code is available to accompany this topic: Download. 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 Studio or Visual Web Developer Express. Note If you are using Visual Studio, the walkthrough assumes that you selected the Web Developmentcollection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings.  Microsoft Data Access Components (MDAC) version 2.7 or later. If you are using the Microsoft Windows XP or Windows Server 2003 operating systems or later, 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 Developer Center on the MSDN Web site.  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 This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio. To create a new file system Web site 1. Open Visual Studio or Visual Web Developer Express.
  • 63. 2. In the File menu, click New Web Site. The New Web Site dialog box is displayed. 3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Web Site. 4. In the Web location box, select File System, and then enter the name of the folder where you want to keep the pages for your Web site. For example, type the folder name C:WebSites. 5. Click OK. Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script files), and for authentication (ASP.NET membership). 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. o If the Data source list does not display Microsoft SQL Server (SqlClient), click Change, and in theChange Data Source dialog box, select Microsoft SQL Server. o 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 Database 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 Installed Templates, click Visual C# or Visual Basic, and then select Web Form.
  • 64. 3. In the Name box, type EditEmployees.aspx. 4. Click Add. The EditEmployees.aspx page opens in Source view. 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 Datagroup, 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: o It is more secure than storing it in the page. o 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 theName box, click Employees. 8. Under Columns, select the EmployeeID, LastName, FirstName, and HireDate check boxes, and then clickNext. 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 GridViewcontrol and configure it so that you can edit individual records.
  • 65. Note The GridView control presents a list of records and allows you to edit them. However, it does not allow you to insert them. Later 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 theChoose 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 procedure 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
  • 66. User input in an ASP.NET Web page can include potentially malicious client script. By default, ASP.NET Web pages validate user input to make sure input does not include script or HTML elements. 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. 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.