Using the GridView Control

The GridView control is the workhorse of the ASP.NET Framework. It is one of the most feature-rich and complicated of all the ASP.NET controls. The GridView control enables you to display, select, sort, page, and edit data items such as database records.

GridView Control Fundamentals
In this section, you learn how to take advantage of all the basic features of the GridView control. In particular, you learn how to display, select, sort, page, and edit database data
with a GridView control. We also discuss GridView formatting options.

Displaying Data
The GridView renders its data items in an HTML table. Each data item is rendered in a distinct HTML table row. For example, the page in Listing demonstrates how you can use the GridView to display the contents of the Movies database table (see Figure)




In Listing , the GridView control is bound to a SqlDataSource control, which represents the Movies database table. The GridView is associated with its data source through its DataSourceID property. Notice that the GridView control automatically renders a check box for any Boolean fields. In the case of Listing , the GridView renders a check box for the InTheaters database column. For all other types of fields, the GridView simply renders the contents of the field.

The GridView control was designed to meet XHTML and accessibility guidelines. For example, the control uses the <th> tag to render its headers. Furthermore, each header tag includes a scope=”col” attribute.

You can add a GridView and SqlDataSource control to a page quickly by dragging a database table from the Database Explorer window onto a page in Design view. When you drag a database table onto the page, a SqlDataSource is automatically created, which retrieves all the rows and all the columns from a database table.

Selecting Data
You can enable a user to select a particular row in a GridView control. This is useful when you want to build single-page Master/Details forms. For example, the page in Listing.


Notice that the first GridView has its AutoGenerateSelectButton property enabled. When this property has the value True, a Select link is displayed next to each row. You can determine which row is selected in a GridView control by using any of the following methods:
  • SelectedDataKey()—Returns the DataKey object associated with the selected row (useful when there are multiple data keys).
  • SelectedIndex()—Returns the (zero-based) index of the selected row.
  • SelectedValue()—Returns the data key associated with the selected row.
  • SelectedRow()—Returns the actual row (GridViewRow object) associated with the selected row.


In most cases, you use the SelectedValue() method to determine the value associated with a particular row. The SelectedValue() method returns the data key associated with a  row. The following section discusses data keys.

If you want to customize the appearance of the Select link, then you can use a CommandField control instead of using the AutoGenerateSelectButton property. The CommandField control is discussed later in this chapter in the section entitled “Using Fields with the GridView Control.”

Using Data Keys
You associate a value with each row in a GridView by providing a value for the GridView control’s DataKeyNames property. You can assign the name of a single database column to this property or you can assign a comma-separated list of column names to this property.


Paging Through Data
When working with a large number of database rows, it is useful to be able to display the rows in different pages. You can enable paging with the GridView control by enabling its AllowPaging property.

The PagerSettings class supports the following properties:
  • FirstPageImageUrl—Enables you to display an image for the first page link.
  • FirstPageText—Enables you to specify the text for the first page link.
  • LastPageImageUrl—Enables you to display an image for the last page link.
  • LastPageText—Enables you to specify the text for the last page link.
  • Mode—Enables you to select a display mode for the pager user interface. Possible values are NextPrevious, NextPreviousFirstLast, Numeric, and NumericFirstLast.
  • NextPageImageUrl—Enables you to display an image for the next page link.
  • NextPageText—Enables you to specify the text for the next page link.
  • PageButtonCount—Enables you to specify the number of page number links to display.
  • Position—Enables you to specify the position of the paging user interface. Possible values are Bottom, Top, and TopAndBottom.
  • PreviousPageImageUrl—Enables you to display an image for the previous page link.
  • PreviousPageText—Enables you to specify the text for the previous page link.
  • Visible—Enables you to hide the paging user interface.

Using ViewState with the GridView Control
By default, the GridView control stores the values of all the columns contained in all the rows that it renders in ViewState. In other words, all the rows that the GridView retrieves from its data source are stuffed in a hidden form field. The advantage of using ViewState is that the GridView does not need to query the database for the same set of records every time a page containing the GridView is displayed. The records are retrieved from the database only when the page first loads.

The disadvantage of using ViewState is that it means that a lot of information might need to be pushed over the wire to a user’s browser. All ViewState information is stored in a hidden form field. When a large number of rows are displayed, this hidden form field can become enormous. When ViewState becomes too large, it can significantly impact a page’s performance.

You can disable ViewState by assigning the value False to the GridView control’s EnableViewState property. Even if you disable ViewState, you can still display, sort, page, and edit database records with the GridView control. (The GridView uses ControlState to track vital state information.) When displaying a large number of records, you should turn ViewState off.

You can view the amount of ViewState that a GridView is using by enabling tracing for the page that contains the GridView. Add the Trace=”True” attribute to the Page directive like this:

<%@ Page Trace=”true” %>

When tracing is enabled, a Control Tree section is appended to the end of a page when the page is rendered in a browser. The Control Tree section displays the ViewState size used by each control contained in the page.

Using Fields with the GridView Control
In all the sample code in the previous section, the GridView control was used to render automatically an HTML table that contains a list of data items. However, there is a problem with allowing the GridView to render its columns automatically. The result does not look very professional.

For example, the column headers are simply the names of the underlying database columns. Displaying the column name EntryDate as a column header seems, well, a little cheesy. We really need to be able to specify custom column headers. Another problem with enabling the GridView to render its columns automatically is that you give up any control over column formatting. For example, the BoxOfficeTotals column is displayed as a decimal amount without any currency formatting. The EntryDate column always displays in short-date and long-time format. Furthermore, it would be nice to be able to display the values of certain columns as
images, drop-down lists, or hyperlinks. If you use the automatically generated columns, then you are stuck with the user interface you are given.

The solution to all these problems is to specify explicitly the fields that a GridView displays. The GridView control supports the following types of fields:
  • BoundField—Enables you to display the value of a data item as text.
  • CheckBoxField—Enables you to display the value of a data item as a check box.
  • CommandField—Enables you to display links for editing, deleting, and selecting rows.
  • ButtonField—Enables you to display the value of a data item as a button (image button, link button, or push button).
  • HyperLinkField—Enables you to display the value of a data item as a link.
  • ImageField—Enables you to display the value of a data item as an image.
  • TemplateField—Enables you to customize the appearance of a data item.


Working with GridView Control Events
The GridView control includes a rich set of events that you can handle to customize the control’s behavior and appearance. These events can be divided into three groups. First, the GridView control supports the following set of events that are raised when the control displays its rows:
  • DataBinding—Raised immediately before the GridView is bound to its data source.
  • DataBound—Raised immediately after a GridView is bound to its data source.
  • RowCreated—Raised when each row in the GridView is created.
  • RowDataBound—Raised when each row in the GridView is bound to data.


Second, the GridView control includes the following set of events that are raised when you
are editing records:
  • RowCommand—Raised when an event is raised by a control contained in the GridView.
  • RowUpdating—Raised immediately before a GridView updates a record.
  • RowUpdated—Raised immediately after a GridView updates a record.
  • RowDeleting—Raised immediately before a GridView deletes a record.
  • RowDeleted—Raised immediately after a GridView deletes a record.
  • RowCancelingEdit—Raised when you cancel updating a record.


Finally, the GridView control supports the following events related to sorting, selecting, and paging:
  • PageIndexChanging—Raised immediately before the current page is changed.
  • PageIndexChanged—Raised immediately after the current page is changed.
  • Sorting—Raised immediately before sorting.
  • Sorted—Raised immediately after sorting.
  • SelectedIndexChanging—Raised immediately before a row is selected.
  • SelectedIndexChanged—Raised immediately after a row is selected.





1 comment: