Partager via


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:

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

  1. Open Visual Web Developer.

  2. On the File menu, click New, and then click Web Site. If you are using Visual Web Developer Express, on the File menu, click New Web Site.

    The New Web Site dialog box appears.

  3. Under Visual Studio installed templates, click ASP.NET Web Site.

  4. In the Location box, enter the name of the folder where you want to keep the pages of the Web site.

    For example, type the folder name C:\WebSites\FormViewData.

  5. In the Language list, click the programming language you prefer to work in.

    Click OK.

To add the Northwind sample database file to the Web site

  1. 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.

  2. In Solution Explorer, right-click the App_Data folder, and then click Add Existing Item.

    The Add Existing Item dialog box is displayed.

  3. 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

  1. Switch to or open the Default.aspx page

  2. Switch to Design view.

  3. Type Display Product Information in the page.

  4. From the Standard group in the Toolbox, drag a DropDownList control onto the page.

  5. If the DropDownList Tasks menu does not appear, right-click the DropDownList control, and then click Show Smart Tag.

  6. On the DropDownList Tasks menu, select the Enable AutoPostBack check box.

  7. Click Choose Data Source to open the Data Source Configuration Wizard.

  8. In the Select a data source list, click <New Data Source>.

  9. Click Database.

    This specifies that you want to get data from a database that supports SQL statements.

    In the Specify an ID for the data source box, a default data source control name of SqlDataSource1 is displayed. You can leave this name.

  10. Click OK.

    The wizard displays a page where you can select a connection.

  11. Click the New Connection button.

    The Add Connection dialog box appears.

    • If the Data source list does not display Microsoft SQL Server 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.

  12. Click Next.

  13. 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.

  14. Click Specify columns from a table or view.

  15. In the Name list, click Products.

  16. Under Columns, select ProductID and ProductName.

  17. Click Next.

  18. Click Test Query to make sure that you are retrieving the data that you want.

  19. Click Finish.

    You are returned to the wizard.

  20. In the Select a data field to display in the DropDownList list, click ProductName.

  21. 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.

  22. Click OK.

You can now 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 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

  1. From the Data group in the Toolbox, drag a FormView control onto page.

  2. If the FormView Tasks menu does not appear, right-click the FormView control, and then click Show Smart Tag.

  3. On the FormView Tasks menu, in the Choose Data Source list, click <New Data Source>.

    The Data Source Configuration Wizard dialog box appears.

  4. Click Database.

    The FormView control will get data from the same table as the DropDownList control.

    In the Specify an ID for the data source box, a default data source control name of SqlDataSource2 is displayed. You can leave this name.

  5. Click OK.

    The Configure Data Source wizard starts.

  6. From the Which data connection should your application use to connect to the database? list, select the connection that you created and stored earlier in the walkthrough.

  7. Click Next.

    The wizard displays a page where you can create a SQL statement.

  8. From the Name list under Specify columns from a table or view, select Products.

  9. In the Columns box, select ProductID, ProductName, and UnitPrice.

  10. Click the WHERE button.

    The Add WHERE Clause dialog box is displayed.

  11. From the Column list, select ProductID.

  12. In the Operator list, make sure that = is selected.

  13. From the Source list, select Control.

  14. Under Parameter properties, in the Control ID list, select DropDownList1.

    The last two steps specify that the query will get the search value for the product ID from the DropDownList control you added earlier.

  15. Click Add.

  16. Click OK to close the Add WHERE Clause dialog box.

  17. Click Advanced.

    The Advanced SQL Generation Options dialog box appears.

  18. Select the Generate INSERT, UPDATE, and DELETE statements check box.

    This option causes the wizard to create SQL update statements based on the Select statement you have configured. Later in the walkthrough you will use the FormView control to modify and insert records, which requires update statements in the data source control.

  19. Click OK.

  20. Click Next.

  21. In the Preview page, click Test Query.

    The wizard displays a dialog box that prompts you for a value to use in the WHERE clause.

  22. In the Value box, type 4 and then click OK.

    The product information appears.

  23. Click Finish.

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

  1. Press CTRL+F5 to run the page.

  2. In the DropDownList control, click a product name.

    The FormView control displays details about that product.

  3. Select a different product and confirm that the FormView control displays the product details.

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

  1. Click the FormView control to select it, and then drag the resize handle on the right side of the control to make the control as wide as the current page.

  2. Drag the resize handle on the bottom of the control to change the height of the control to about 400 pixels. (The exact height is not important.)

  3. Right-click the control, click Edit Template, and then click ItemTemplate.

    The control is redisplayed in item-template editing mode. The item template contains the static text and controls that are used to display the data record when the page runs. By default, Visual Web Developer populates the item template with a data-bound Label control for each data column in the data source. In addition, Visual Web Developer generates static text for each label to act as a caption.

    The template is also generated with three LinkButton controls with the text Edit, Delete, and New.

  4. Put the 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.

  5. 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.

  6. In the Insert Table dialog box, set Rows to 4 and Columns to 2.

  7. Click OK to close the Insert Table dialog box.

  8. Drag the ProductIdLabel control into the upper-right cell.

  9. Drag the ProductNameLabel control into the second right-hand cell.

  10. Drag the UnitPriceLabel control into the third right-hand cell.

  11. In the left-hand column, type static text to act as captions for the Label controls. For example, in the cell next to the ProductIdLabel control, type ID. You can type any caption text that you like.

  12. Right-click the left-hand top cell, and in the Properties window, set align to right to make the caption text right-aligned.

  13. Repeat the previous step for the next two left-hand cells.

  14. Select the right-hand column and drag its right-hand border to make the table wide enough to display long product names.

  15. Select the text generated by Visual Web Developer (for example, the text ProductID) and delete it.

  16. Right-click the FormView control's title bar and 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

  1. Press CTRL+F5 to run the page.

  2. In the DropDownList control, click a product name.

    The FormView control displays details about that product.

  3. Select a different product and confirm that the FormView control displays the product details.

  4. Close the browser.

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

  1. Switch to Design view.

  2. Select the FormView control.

  3. In the Properties window, click the Events button to display a list of events for the FormView control.

  4. Double-click the ItemInserted box.

    Visual Web Developer switches to code-editing view and creates a handler for the ItemInserted event.

  5. 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.

  6. Create handlers and add the DataBind call for the ItemDeleted and ItemUpdated events.

  7. Press CTRL+F5 to run the page.

  8. 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.

  9. 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

  1. Switch to Design view.

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

    Visual Web Developer creates an event handler for the page's Load event.

  3. 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.

  4. In Design view, select the DropDownList control.

  5. In the Properties window, click the ellipsis button (...) in the Items box.

    The ListItem Collection Editor dialog box appears.

  6. Click Add to create a new item.

  7. Under ListItem properties, in the Text box, type (Select).

  8. Click OK to close the ListItem Collection Editor dialog box.

  9. 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.

  10. In the Properties window, click the Events button to display a list of events for the DropDownList control.

  11. Double-click the SelectedIndexChanged box.

  12. 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.

  13. Press CTRL+F5 to run the page.

    The page displays only the drop-down list, with the word "(Select)" displayed.

  14. 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

Reference

DetailsView Web Server Control Overview