Export (0) Print
Expand All
14 out of 28 rated this helpful - Rate this topic

Walkthrough: Displaying Formatted Data in Web Pages with the FormView Web Server Control 

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

NoteNote

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 (Visual Studio).

Tasks illustrated in this walkthrough include:

  • Creating a page to display master/detail information.

  • Using a FormView control to create a free-form layout for a data record.

  • Configuring the FormView control to allow editing.

In order to complete this walkthrough, you will need:

  • Microsoft Visual Web Developer.

  • Access to the SQL Server Northwind database. For information about downloading and installing the SQL Server sample Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site.

    NoteNote

    If you need information about how to log on to the computer running SQL Server, contact the server administrator.

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

    If you are using Microsoft Windows XP or Windows Server 2003, you already have MDAC 2.7. However, if you are using Microsoft Windows 2000, you might need to upgrade the MDAC already installed on your computer. For more information, see "Microsoft Data Access Components (MDAC) Installation" in the MSDN Library.

Create a new Web site and page by following these steps.

To create a file system Web site

  1. Open Visual Web Developer.

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

    The New Web Site dialog box appears.

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

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

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

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

  6. Click OK.

    Visual Web Developer creates the folder and a new page named Default.aspx.

In this part of the walkthrough, you will add a drop-down list to a page and populate it with a list of product names. When users select a product, the page will display the details for that product in a FormView control.

To create and populate a drop-down list

  1. Switch to or open the Default.aspx page. If you are working with a Web site you had already created, add or open a page that you can work with in this walkthrough.

  2. Switch to Design view.

  3. Type Display Product Information in the page.

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

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

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

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

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

  9. Click Database.

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

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

  10. Click OK.

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

  11. Click the New Connection button.

    The Add Connection dialog box appears.

    • If the Data source list does not display Microsoft SQL Server (SqlClient), click Change, and in the Change Data Source dialog box, select Microsoft SQL Server.

    • If the Choose Data Source page appears, in the Data source list, select the type of data source you will use. For this walkthrough, the data source type is Microsoft SQL Server. In the Data provider list, click .NET Framework Data Provider for SQL Server, and then click Continue.

  12. In the Add Connection dialog box, do the following:

    1. In the Server name box, enter the name of the computer running SQL Server.

    2. For the logon credentials, select the option that is appropriate to access the running the SQL Server database (integrated security or specific ID and password) and, if required, enter a user name and password. Select the Save my Password check box if you entered a password.

    3. Select the Select or enter a database name button, and then enter Northwind.

    4. Click Test connection, and when you are sure that the connection works, click OK.

    You are returned to the wizard, and the connection information is filled in.

  13. Click Next.

  14. Be sure that the Yes, save this connection as check box is selected, and then click Next. (You can leave the default connection string name.)

    The wizard displays a page where you can specify what data you want to retrieve from the database.

  15. Click Specify columns from a table or view.

  16. In the Name list, click Products.

  17. Under Columns, select ProductID and ProductName.

  18. Click Next.

  19. Click Test Query to be sure that you are retrieving the data you want.

  20. Click Finish.

    You are returned to the wizard.

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

  22. From the Select a data field for the value of the DropDownList list, select ProductID.

    This specifies that when an item is selected, the ProductID field will be returned as the value of the item.

  23. Click OK.

Before proceeding, test the drop-down list.

To test the drop-down list

  1. Press CTRL+F5 to run the page.

  2. When the page is displayed, examine the drop-down list.

  3. Select a product name to be sure that the list performs a postback.

You will now add a FormView control to display product details. The FormView control gets its data from a second data source control that you add to the page. The second data source control contains a parameterized query that gets the product record for the item currently selected in the DropDownList control.

To add a FormView control

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

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

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

    The Data Source Configuration Wizard dialog box appears.

  4. Click Database.

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

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

  5. Click OK.

    The Configure Data Source wizard starts.

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

  7. Click Next.

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

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

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

  10. Click the WHERE button.

    The Add WHERE Clause dialog box is displayed.

  11. From the Column list, select ProductID.

  12. From the Operator list, select =.

  13. From the Source list, select Control.

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

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

  15. Click Add.

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

  17. Click Advanced.

    The Advanced SQL Generation Options dialog box appears.

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

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

  19. Click OK.

  20. Click Next.

  21. In the Preview page, click Test Query.

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

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

    The product information appears.

  23. Click Finish.

The reason to use the FormView control is that you can define the layout of the record that it displays. In this section of the walkthrough, you will customize the record layout by editing a template. For your layout, you will use an HTML table.

To format the layout

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

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

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

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

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

  4. Put the insertion point at the top of the item template, press ENTER a few times to make room, and then at the top of the template type Product Details to act as a heading.

  5. Put the insertion point below the controls and static text and, in the Layout menu, click Insert Table.

    You are creating an HTML table as a container for the text and controls.

  6. In the Insert Table dialog box, do the following:

    1. Set Rows to 4.

    2. Set Columns to 2.

    3. Click the Cell Properties button, and set Width to 35 pixels (px) and Height to 30 pixels (px).

  7. Click OK to close the Cell Properties dialog box, and then click OK to close the Insert Table dialog box.

  8. Drag the ProductIdLabel control into the top right-hand cell.

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

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

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

  12. Right-click the left-hand column, click Select, and then click Column.

  13. In the Properties window, set align to right to make the caption text right-aligned.

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

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

  16. Right-click the FormView control's title bar and click End Template Editing.

    The template editor closes and the control appears with the layout you have created.

Testing the FormView Control

You can now test your layout.

To test the FormView control

  1. Press CTRL+F5 to run the page.

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

    The FormView control displays details about that product.

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

  4. Close the browser.

The FormView control can display individual records and also supports editing, deleting, and inserting.

In this part of the walkthrough, you will add the ability to edit the currently displayed record. To edit the record, you define a different template that contains text boxes (and potentially other controls).

To add editing capability to the FormView control

  1. Right-click the FormView control, click Edit Template, and click EditItemTemplate.

    The template editor appears, displaying the EditItemTemplate property, which defines how records are laid out when the control is in edit mode. Visual Web Developer populates the edit template with a TextBox control for each data column that is not a key and adds static text for captions. This is similar to the way the item template was generated, except that in the edit template, Visual Web Developer generates text boxes.

    As before, the template is generated with Update and Cancel LinkButton controls that are used to save and discard changes while editing.

  2. Optionally, add a layout table and arrange the controls as you did when working with the item template earlier in the walkthrough.

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

    As with the EditItemTemplate property, Visual Web Developer automatically creates a template layout of labels and TextBox controls. The controls will be displayed when users want to insert a new record into the Products table. The template is also generated with Insert and Cancel LinkButton controls.

  4. Optionally, add a layout table and arrange the controls as you did when working with the edit item template.

  5. Right-click the FormView control and click End Template Editing.

    Security noteSecurity 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.

Testing Editing and Inserting

You can now test editing and inserting.

To test editing capabilities of the FormView control

  1. Press CTRL+F5 to run the page.

  2. Select a product in the DropDownList control.

    The product details appear in the FormView control.

  3. Click Edit.

    The FormView control switches to edit mode.

  4. Make a change to the product name or unit price.

  5. Click Update.

    The record is saved and the FormView control switches to display mode. The change is reflected in the display.

  6. Select a different product.

  7. Click Edit.

  8. Make a change to the product name.

  9. Click Cancel.

    Confirm that the change was not saved.

To test insert capabilities of the FormView control

  1. Click New in the FormView control.

    The FormView control switches to insert mode, displaying two empty text boxes.

  2. Enter a new product name and price, and then click Insert.

    The record is saved in the database and the FormView control switches to display (ItemTemplate) view.

    NoteNote

    The new record is not displayed in the drop-down list. You will add that capability in the next section.

Your page now allows you to view, edit, or delete records in the Products database table. However, the drop-down list is not yet synchronized with changes that you make in the FormView control. For example, if you insert a new Products record, the drop-down list does not display the new record unless you close the page and reopen it. In addition, the page is displayed initially with the first record in the Products table, which might not be what you want.

You can add some code to fix these minor issues. In this section of the walkthrough, you will do the following:

  • Update the drop-down list whenever users edit or insert a record.

  • Add the text "(Select)" to the drop-down list when the page first appears, and remove it when the user has made the first selection.

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

  1. In Design view of the page, select the FormView control.

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

  3. Double-click the ItemInserted box.

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

  4. Add the following highlighted code to the event handler.

    Protected Sub FormView1_ItemInserted(ByVal sender As Object, _
       ByVal e As System.Web.UI.WebControls.FormViewInsertedEventArgs) _
       Handles FormView1.ItemInserted
          DropDownList1.DataBind()
    End Sub
    

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

    The code runs after the new record has been inserted. It re-binds the drop-down list to the Products table, which causes the contents of the list to be refreshed.

  5. Switch to Design view. (If you are working with a code-behind page, switch to the Default.aspx page and then switch to Design view.)

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

  7. Double-click the ItemUpdated box.

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

  8. Add the following highlighted code.

    Protected Sub FormView1_ItemUpdated(ByVal sender As Object, _
       ByVal e As System.Web.UI.WebControls.FormViewUpdatedEventArgs) _
       Handles FormView1.ItemUpdated
          DropDownList1.DataBind()
    End Sub
    

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

    The code runs after the record has been updated. It re-binds the drop-down list to the Products table, which causes the contents of the list to be refreshed.

  9. Press CTRL+F5 to run the page.

  10. Edit the product name of a record, click Update, and then examine the drop-down list to be sure that the updated name is displayed.

  11. Insert a new product record, click Insert, and then examine the drop-down list to be sure that the new name has been added to the list.

The final step is to change the drop-down list to display "(Select)" and to display the FormView control only when users have made a selection.

To add a Select entry to the DropDownList control

  1. In Design view, double-click a blank part of the page.

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

  2. In the handler, add the following highlighted code.

    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
    

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

    The code runs when the page runs. It tests first to see if this is a postback; if not, this is the first time the page has run. If it is not a postback, the code hides the FormView control, because you want to display it only when the user has explicitly selected a record to view or edit.

  3. In Design view for the page, select the DropDownList control.

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

    The ListItem Collection Editor dialog box appears.

  5. Click Add to create a new item.

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

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

  8. In the Properties box, set AppendDataBoundItems to true.

    When the drop-down list is populated during data binding, the product information will be added to the (Select) item you defined.

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

  10. Double-click the SelectedIndexChanged box.

  11. Add the following highlighted code.

    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
    

    protected void DropDownList1_SelectedIndexChanged(object sender, 
        EventArgs e)
    {
        if(DropDownList1.Items[0].Text == "(Select)")
        {
            DropDownList1.Items.RemoveAt(0);
        }
        FormView1.Visible = true;
    }
    

    The code runs when users select an item in the DropDownList control. It removes the "(Select)" item that you added earlier (checking first to be sure it exists), because after the first time users have selected an item, you no longer need to prompt them to select an item. The code also displays (un-hides) the FormView control so that users can see the record they have selected.

  12. Press CTRL+F5 to run the page.

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

  13. Select an item in the list.

    The item is displayed in the FormView control.

  14. Examine the drop-down list and note that the word (Select) is no longer in the list.

This walkthrough has shown you the basic steps for using a FormView control to display and edit individual data records using a custom layout. The FormView control allows you to perform more sophisticated formatting than what you have done in this walkthrough. In addition, you can create templates for other modes, including selection mode and insertion mode, and for headers and footers that are displayed with the record. For other scenarios to explore with the FormView, see the following:

Creating Templates for the FormView Web Server Control

Modifying Data Using a FormView Web Server Control

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.