Walkthrough: Displaying Formatted Data in Web Pages with the FormView Web Server Control
ASP.NET provides various controls that let you display and edit data records. In this walkthrough, you will work with the FormView control, which works with a single data record at a time. The FormView control's primary feature is that it lets you create the record layout yourself by defining templates. By working with templates, you can have complete control over the layout and appearance of the data in the control. The FormView control also supports updates such as editing, inserting, and deleting data records. If the data source provides more than one record to the FormView control, the control lets you page through the records individually.
A Visual Studio project with source code is available to accompany this topic: Download.
Tasks illustrated in this walkthrough include the following:
Creating a page to display master/detail information.
Using a FormView control to create a free-form layout for a data record.
Configuring the FormView control to enable editing.
Prerequisites
In order to complete this walkthrough, you will need:
Microsoft Visual Studio 2008 Service Pack 1 or Visual Web Developer 2008 Express Edition Service Pack 1.
installed on your computer. A basic edition of is included with Visual Studio. To download a more advanced version that includes tools, services, and full-text search, see Microsoft SQL Server Express 2008 with Advanced Services on the Microsoft download Web site.
The Northwind sample database installed on your computer. For information about how to download and install the SQL Server sample Northwind database, see How to: Set Up the Northwind Sample Database for ASP.NET Development.
Creating the Web Site
In the first part of the walkthrough, you will create a new Web site and add the Northwind sample database to it.
To create a file system Web site
Open Visual Web Developer.
On the File menu, click New, and then click Web Site. If you are using Visual Web Developer Express, on the File menu, click New Web Site.
The New Web Site dialog box appears.
Under Visual Studio installed templates, click ASP.NET Web Site.
In the Location box, enter the name of the folder where you want to keep the pages of the Web site.
For example, type the folder name C:\WebSites\FormViewData.
In the Language list, click the programming language you prefer to work in.
Click OK.
To add the Northwind sample database file to the Web site
If the project does not contain an App_Data folder, in Solution Explorer, right-click the project name, click Add ASP.NET Folder, and then click App_Data.
In Solution Explorer, right-click the App_Data folder, and then click Add Existing Item.
The Add Existing Item dialog box is displayed.
Browse to the folder that contains the .mdf file for the Northwind database, select the Northwind.mdf file, and then click Add.
This creates a copy of the database and adds it to your Web site or project.
Using a Drop-Down List as the Master
In this part of the walkthrough, you will add a drop-down list to a page and populate it with a list of product names. When users select a product, the page will display the details for that product in a FormView control.
To create and populate a drop-down list
Switch to or open the Default.aspx page
Switch to Design view.
Type Display Product Information in the page.
From the Standard group in the Toolbox, drag a DropDownList control onto the page.
If the DropDownList Tasks menu does not appear, right-click the DropDownList control, and then click Show Smart Tag.
On the DropDownList Tasks menu, select the Enable AutoPostBack check box.
Click Choose Data Source to open the Data Source Configuration Wizard.
In the Select a data source list, click <New Data Source>.
Click Database.
This specifies that you want to get data from a database that supports SQL statements.
In the Specify an ID for the data source box, a default data source control name of SqlDataSource1 is displayed. You can leave this name.
Click OK.
The wizard displays a page where you can select a connection.
Click the New Connection button.
The Add Connection dialog box appears.
If the Data source list does not display Microsoft SQL Server Database File (SqlClient), click Change, and in the Change Data Source dialog box, select Microsoft SQL Server Database File (SqlClient).
Use the Browse button to navigate to the App_Data\Northwnd.mdf file in your Web site. The Database file name (new or existing) text box displays the path to the Northwind.mdf file.
Click Test connection. When the test succeeds, close the Add Connection dialog box.
You are returned to the wizard, and the connection information is filled in.
Click Next.
Be sure that the Yes, save this connection as check box is selected, and then click Next. (You can leave the default connection string name.)
The wizard displays a page where you can specify what data you want to retrieve from the database.
Click Specify columns from a table or view.
In the Name list, click Products.
Under Columns, select ProductID and ProductName.
Click Next.
Click Test Query to make sure that you are retrieving the data that you want.
Click Finish.
You are returned to the wizard.
In the Select a data field to display in the DropDownList list, click ProductName.
From the Select a data field for the value of the DropDownList list, select ProductID.
This specifies that when an item is selected, the ProductID field will be returned as the value of the item.
Click OK.
You can now test the drop-down list.
To test the drop-down list
Press CTRL+F5 to run the page.
When the page is displayed, examine the drop-down list.
Select a different product name to make sure that the list performs a postback.
Adding a FormView Control
You will now add a FormView control to display product details. The FormView control gets its data from a second data source control that you add to the page. The second data source control contains a parameterized query that gets the product record for the item currently selected in the DropDownList control.
To add a FormView control
From the Data group in the Toolbox, drag a FormView control onto page.
If the FormView Tasks menu does not appear, right-click the FormView control, and then click Show Smart Tag.
On the FormView Tasks menu, in the Choose Data Source list, click <New Data Source>.
The Data Source Configuration Wizard dialog box appears.
Click Database.
The FormView control will get data from the same table as the DropDownList control.
In the Specify an ID for the data source box, a default data source control name of SqlDataSource2 is displayed. You can leave this name.
Click OK.
The Configure Data Source wizard starts.
From the Which data connection should your application use to connect to the database? list, select the connection that you created and stored earlier in the walkthrough.
Click Next.
The wizard displays a page where you can create a SQL statement.
From the Name list under Specify columns from a table or view, select Products.
In the Columns box, select ProductID, ProductName, and UnitPrice.
Click the WHERE button.
The Add WHERE Clause dialog box is displayed.
From the Column list, select ProductID.
In the Operator list, make sure that = is selected.
From the Source list, select Control.
Under Parameter properties, in the Control ID list, select DropDownList1.
The last two steps specify that the query will get the search value for the product ID from the DropDownList control you added earlier.
Click Add.
Click OK to close the Add WHERE Clause dialog box.
Click Advanced.
The Advanced SQL Generation Options dialog box appears.
Select the Generate INSERT, UPDATE, and DELETE statements check box.
This option causes the wizard to create SQL update statements based on the Select statement you have configured. Later in the walkthrough you will use the FormView control to modify and insert records, which requires update statements in the data source control.
Click OK.
Click Next.
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.
In the Value box, type 4 and then click OK.
The product information appears.
Click Finish.
Testing the FormView Control
You now have a fully functional form view that enables you to modify, insert and delete data.
To test the FormView control
Press CTRL+F5 to run the page.
In the DropDownList control, click a product name.
The FormView control displays details about that product.
Select a different product and confirm that the FormView control displays the product details.
Customizing the Layout in the FormView Control
The reason to use the FormView control instead of a DetailsView control is that you can define the layout of the record that the FormView control displays. The DetailsView control provides a fixed view that is simpler but has less layout flexibility. In this section of the walkthrough, you will customize the record layout by editing a template. For your layout, you will use an HTML table.
To format the layout
Click the FormView control to select it, and then drag the resize handle on the right side of the control to make the control as wide as the current page.
Drag the resize handle on the bottom of the control to change the height of the control to about 400 pixels. (The exact height is not important.)
Right-click the control, click Edit Template, and then click ItemTemplate.
The control is redisplayed in item-template editing mode. The item template contains the static text and controls that are used to display the data record when the page runs. By default, Visual Web Developer populates the item template with a data-bound Label control for each data column in the data source. In addition, Visual Web Developer generates static text for each label to act as a caption.
The template is also generated with three LinkButton controls with the text Edit, Delete, and New.
Put the cursor at the top of the item template, press ENTER a few times to make room, and then at the top of the template type Product Details to act as a heading.
Put the cursor below the Product Details heading and then in the Table menu, click Insert Table.
You are creating an HTML table as a container for the text and controls.
In the Insert Table dialog box, set Rows to 4 and Columns to 2.
Click OK to close the Insert Table dialog box.
Drag the ProductIdLabel control into the upper-right cell.
Drag the ProductNameLabel control into the second right-hand cell.
Drag the UnitPriceLabel control into the third right-hand cell.
In the left-hand column, type static text to act as captions for the Label controls. For example, in the cell next to the ProductIdLabel control, type ID. You can type any caption text that you like.
Right-click the left-hand top cell, and in the Properties window, set align to right to make the caption text right-aligned.
Repeat the previous step for the next two left-hand cells.
Select the right-hand column and drag its right-hand border to make the table wide enough to display long product names.
Select the text generated by Visual Web Developer (for example, the text ProductID) and delete it.
Right-click the FormView control's title bar and then click End Template Editing.
The template editor closes and the control appears with the layout you have created.
Testing the FormView Control
You can now test your layout.
To test the FormView control
Press CTRL+F5 to run the page.
In the DropDownList control, click a product name.
The FormView control displays details about that product.
Select a different product and confirm that the FormView control displays the product details.
Close the browser.
Redisplaying Updated Product Names in the Drop-Down List
The page lets you view, edit, insert, and delete records in the Products table. However, the drop-down list is not yet synchronized with changes that you make in the FormView control. For example, if you insert a new Products record, the drop-down list does not display the new record unless you close the page and reopen it. In addition, the page is displayed at first with the first record in the Products table, which might not be what you want.
You can add some code to fix these issues. In this section of the walkthrough, you will do the following:
Update the drop-down list whenever users edit, insert, or delete a record.
Add the text "(Select)" to the drop-down list when the page first appears, and remove it when the user has made the first selection.
To update the drop-down list when records are edited, deleted, or inserted
Switch to Design view.
Select the FormView control.
In the Properties window, click the Events button to display a list of events for the FormView control.
Double-click the ItemInserted box.
Visual Web Developer switches to code-editing view and creates a handler for the ItemInserted event.
In the item-inserted event handler, call the DataBind method of the drop-down list control, as shown in the following example:
Protected Sub FormView1_ItemInserted(ByVal sender As Object, _ ByVal e As System.Web.UI.WebControls.FormViewInsertedEventArgs) _ Handles FormView1.ItemInserted DropDownList1.DataBind() End Sub
[C#]
protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e) { DropDownList1.DataBind(); }
The code runs after the new record has been inserted. It rebinds the drop-down list to the Products table, which causes the contents of the list to be refreshed.
Create handlers and add the DataBind call for the ItemDeleted and ItemUpdated events.
Press CTRL+F5 to run the page.
Edit the product name of a record, click Update, and then examine the drop-down list to make sure that the updated name is displayed.
Insert a new product record, click Insert, and then examine the drop-down list to make sure that the new name has been added to the list.
The final step is to change the drop-down list to display "(Select)" and to display the FormView control only when users have made a selection.
To add a Select entry to the DropDownList control
Switch to Design view.
Double-click a blank part of the page.
Visual Web Developer creates an event handler for the page's Load event.
In the Page_Load handler, hide the FormView control as shown in the following example:
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then FormView1.Visible = False End If End Sub
[C#]
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { FormView1.Visible = false; } }
The code runs when the page loads. It tests first to see whether the page was invoked in response to a postback. If not, this is the first time the page has run. If it is not a postback, the code hides the FormView control, because you want to display the control only when the user has explicitly selected a record to view or edit.
In Design view, select the DropDownList control.
In the Properties window, click the ellipsis button (...) in the Items box.
The ListItem Collection Editor dialog box appears.
Click Add to create a new item.
Under ListItem properties, in the Text box, type (Select).
Click OK to close the ListItem Collection Editor dialog box.
In the Properties window, set AppendDataBoundItems to true.
When the drop-down list is populated during data binding, the product information will be added to the "(Select)" item that you have defined.
In the Properties window, click the Events button to display a list of events for the DropDownList control.
Double-click the SelectedIndexChanged box.
In the generated handler, add the following highlighted code:
[Visual Basic]
Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender _ As Object, ByVal e As System.EventArgs) _ Handles DropDownList1.SelectedIndexChanged If DropDownList1.Items(0).Text = "(Select)" Then DropDownList1.Items.RemoveAt(0) End If FormView1.Visible = True End Sub
[C#]
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { if(DropDownList1.Items[0].Text == "(Select)") { DropDownList1.Items.RemoveAt(0); } FormView1.Visible = true; }
The code runs when users select an item in the DropDownList control. It removes the "(Select)" item that you added earlier (the code makes sure first that the item exists), because after the first time that an item is selected, you no longer have to prompt users to select an item. The code also displays (un-hides) the FormView control so that users can see the record they have selected.
Press CTRL+F5 to run the page.
The page displays only the drop-down list, with the word "(Select)" displayed.
Select an item in the list.
The item is displayed in the FormView control. Notice that the word "(Select)" is no longer in the list.
Next Steps
This walkthrough has shown you the basic steps for using a FormView control to display and edit individual data records using a custom layout. The FormView control lets you perform more sophisticated formatting than what you have done in this walkthrough. In addition, you can create templates for other modes, such as selection mode and insertion mode, and for headers and footers that are displayed with the record. For other scenarios to explore with the FormView, see the following topics:
You can also edit individual data records with the DetailsView control, which provides a predefined layout for the data. For details, see DetailsView Web Server Control Overview.
See Also
Concepts
FormView Web Server Control Overview