DataGrid Web Server Control Declarative Syntax
The DataGrid control renders a tabular, data-bound grid. This control allows you to define various types of columns to control the layout of the cell contents of the grid (bound columns, template columns) and add specific functionality (such as edit button columns, hyperlink columns, and so on). The control also supports a variety of options for paging through data.
<asp:DataGrid
AccessKey="string"
AllowCustomPaging="True|False"
AllowPaging="True|False"
AllowSorting="True|False"
AutoGenerateColumns="True|False"
BackColor="color name|#dddddd"
BackImageUrl="uri"
BorderColor="color name|#dddddd"
BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
Inset|Outset"
BorderWidth="size"
Caption="string"
CaptionAlign="NotSet|Top|Bottom|Left|Right"
CellPadding="integer"
CellSpacing="integer"
CssClass="string"
DataKeyField="string"
DataMember="string"
DataSource="string"
DataSourceID="string"
EditItemIndex="integer"
Enabled="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
Font-Bold="True|False"
Font-Italic="True|False"
Font-Names="string"
Font-Overline="True|False"
Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|
Large|X-Large|XX-Large"
Font-Strikeout="True|False"
Font-Underline="True|False"
ForeColor="color name|#dddddd"
GridLines="None|Horizontal|Vertical|Both"
Height="size"
HorizontalAlign="NotSet|Left|Center|Right|Justify"
ID="string"
OnCancelCommand="CancelCommand event handler"
OnDataBinding="DataBinding event handler"
OnDeleteCommand="DeleteCommand event handler"
OnDisposed="Disposed event handler"
OnEditCommand="EditCommand event handler"
OnInit="Init event handler"
OnItemCommand="ItemCommand event handler"
OnItemCreated="ItemCreated event handler"
OnItemDataBound="ItemDataBound event handler"
OnLoad="Load event handler"
OnPageIndexChanged="PageIndexChanged event handler"
OnPreRender="PreRender event handler"
OnSelectedIndexChanged="SelectedIndexChanged event handler"
OnSortCommand="SortCommand event handler"
OnUnload="Unload event handler"
OnUpdateCommand="UpdateCommand event handler"
PageSize="integer"
runat="server"
SelectedIndex="integer"
ShowFooter="True|False"
ShowHeader="True|False"
SkinID="string"
Style="string"
TabIndex="integer"
ToolTip="string"
UseAccessibleHeader="True|False"
Visible="True|False"
Width="size"
>
<AlternatingItemStyle />
<Columns>
<asp:BoundColumn
DataField="string"
DataFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
ReadOnly="True|False"
SortExpression="string"
Visible="True|False"
>
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:BoundColumn>
<asp:ButtonColumn
ButtonType="LinkButton|PushButton"
CausesValidation="True|False"
CommandName="string"
DataTextField="string"
DataTextFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
SortExpression="string"
Text="string"
ValidationGroup="string"
Visible="True|False"
>
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:ButtonColumn>
<asp:EditCommandColumn
ButtonType="LinkButton|PushButton"
CancelText="string"
CausesValidation="True|False"
EditText="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
SortExpression="string"
UpdateText="string"
ValidationGroup="string"
Visible="True|False"
>
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:EditCommandColumn>
<asp:HyperLinkColumn
DataNavigateUrlField="string"
DataNavigateUrlFormatString="string"
DataTextField="string"
DataTextFormatString="string"
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
NavigateUrl="uri"
SortExpression="string"
Target="string|_blank|_parent|_search|_self|_top"
Text="string"
Visible="True|False"
>
<FooterStyle />
<HeaderStyle />
<ItemStyle />
</asp:HyperLinkColumn>
<asp:TemplateColumn
FooterText="string"
HeaderImageUrl="uri"
HeaderText="string"
SortExpression="string"
Visible="True|False"
>
<FooterStyle />
<HeaderStyle />
<ItemStyle />
<EditItemTemplate>
<!-- child controls -->
</EditItemTemplate>
<FooterTemplate>
<!-- child controls -->
</FooterTemplate>
<HeaderTemplate>
<!-- child controls -->
</HeaderTemplate>
<ItemTemplate>
<!-- child controls -->
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<EditItemStyle />
<FooterStyle />
<HeaderStyle />
<ItemStyle />
<PagerStyle
BackColor="color name|#dddddd"
BorderColor="color name|#dddddd"
BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|
Groove|Ridge|Inset|Outset"
BorderWidth="size"
CssClass="string"
Font-Bold="True|False"
Font-Italic="True|False"
Font-Names="string"
Font-Overline="True|False"
Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|
Medium|Large|X-Large|XX-Large"
Font-Strikeout="True|False"
Font-Underline="True|False"
ForeColor="color name|#dddddd"
Height="size"
HorizontalAlign="NotSet|Left|Center|Right|Justify"
Mode="NextPrev|NumericPages"
NextPageText="string"
OnDisposed="Disposed event handler"
PageButtonCount="integer"
Position="Bottom|Top|TopAndBottom"
PrevPageText="string"
VerticalAlign="NotSet|Top|Middle|Bottom"
Visible="True|False"
Width="size"
Wrap="True|False"
/>
<SelectedItemStyle />
</asp:DataGrid>
Before using the DataGrid control, consider using the GridView control instead. The GridView control is new in the .NET Framework version 2.0 and is the successor to the DataGrid control.
The DataGrid control displays the fields of a data source as columns in a table. Each row in the DataGrid control represents a record in the data source. The DataGrid control supports selection, editing, deleting, paging, and sorting.
By default, the AutoGenerateColumns property is set to true, which creates a BoundColumn object for each field in the data source. Each field is then rendered as a column in the DataGrid control in the order that each field appears in the data source.
You can also manually control which columns appear in the DataGrid control by setting the AutoGenerateColumns property to false and then listing the columns that you want to include between the opening and closing <Columns> tags. The columns specified are added to the Columns collection in the order listed. This allows you to programmatically control the columns in the DataGrid control.
Note |
|---|
| The order that the columns are displayed in the DataGrid control is controlled by the order that the columns appear in the Columns collection. Although you can programmatically change the order of the columns by manipulating the Columns collection, it is easier to list the columns in the desired display order. |
Note |
|---|
| Explicitly declared columns can be used in conjunction with automatically generated columns. When using both, explicitly declared columns will be rendered first, followed by the automatically generated columns. Automatically generated columns are not added to the Columns collection. |
Different column types determine the behavior of the columns in the control. The DataGrid control allows you to use the following types of columns.
| Column type | Description |
|---|---|
| Encapsulates the most common edit commands (Edit, Update, Cancel) in a predefined column type. | |
| Creates a column with a set of hyperlinks that are bound to the value of a data field. For example, a grid that displays a list of orders can include a hyperlink column where the OrderID field is rendered as a hyperlink to a page that displays the details for the order. | |
| Creates a column bound to a field in the data source and rendered in a table cell using styles. This is the default column type for the DataGrid control. | |
| Creates a column that contains a user defined command button, such as Add or Remove, for each item in the column. | |
| Creates a column that allows you to define the layout of controls using templates for custom HTML elements and controls. |
The following tables provide information about the columns you can declare for the DataGrid control.
The following properties are available on all DataGrid column types.
| Property | Description |
|---|---|
| Text to display on the lower edge of the column. | |
| The URL of an image that is rendered in place of HeaderText text in the column header. | |
| Text to display on the upper edge of the column. | |
| A reference to the DataGrid control to which the bound column belongs (read-only). This property is used only when programming. | |
| The name of the field to sort the data source by when the user specifies sorting by the contents of this column. | |
| true if the column is displayed; otherwise, false. |
| Property | Description |
|---|---|
| The field or property of the object in DataSource that is the source of data for the column. | |
| A formatting expression string that specifies how the field is displayed in the cell. This is similar to the formatting expressions used by the Format method. | |
| true if the column cannot be edited when the row is put into edit mode; otherwise, false. |
| Property | Description |
|---|---|
| The type of button to render. The default is LinkButton. When programming, this property is set using the ButtonColumnType. | |
| A string indicating the command that is sent when a button in the column is clicked. This string is available in the event-handling method through the CommandSource property of the e event argument object. The DataGrid control recognizes certain standard command names. These command names include Select, Sort, Update, Cancel, Edit, Delete, and Page. | |
| The field name from the DataSource that is bound to the Text property of the button in the ButtonColumn. | |
| A formatting expression string that specifies how the field is displayed in the cell. | |
| The caption to display on the face of the button in this column. If DataTextField is set, it overrides this value. |
| Property | Description |
|---|---|
| The field or property of the object in DataSource that provides the URL of the page to move to. | |
| A format expression to be used with the Text property. | |
| The field or property of the object in DataSource that is the source of data for the Text property of the columns. | |
| The formatting string that specifies how the Text property is displayed in the control. | |
| The URL of the page to move to. If DataNavigateUrlField is set, it overrides this property. | |
| The target window that displays the page. This can be the name of a window or a frame reference such as _TOP. | |
| The text of the hyperlink. |
| Property | Description |
|---|---|
| The type of button to render. The default is LinkButton. When programming, this property is set using the ButtonColumnType. | |
| The string to display on the face of the Edit button. | |
| The string to display on the face of the Update button. | |
| The string to display on the face of the Cancel button. |
You can customize the appearance of the DataGrid control by setting the style properties of the different parts of the control. The following table lists the style properties for the different parts of the DataGrid control.
| Style property | Description | Style class |
|---|---|---|
| The style of every other item (alternating items). | ||
| The style of the item being edited. | TableItemStyle | |
| The style of the footer at the end of the list (if any). | TableItemStyle | |
| The style of the header at the beginning of the list (if any). | TableItemStyle | |
| The style of individual items. | ||
| The style of the page selection controls. | ||
| The style of the currently selected item. | TableItemStyle |
For information about the properties supported for each style class, see Style Object Properties.
The DataGrid control contains built-in functionality to display its contents in page segments. The number of items on the page is determined by the PageSize property. If no value is specified for the PageSize property, the DataGrid control displays ten items on the page at a time.
By default, paging is disabled. To enable paging, set the AllowPaging property to true and provide code to handle the PageIndexChanged event. The typical logic for the PageIndexChanged event is to set the CurrentPageIndex property to the index of the page to display and then rebind the data source to the control. The index of the page to display is often accessed using the NewPageIndex property of the DataGridPageChangedEventArgs object passed to the event handler.
With standard paging, the DataGrid control assumes that the data source contains all the items to display. The DataGrid control calculates the indexes of the items on the current page based on the page index (specified by the CurrentPageIndex property) and the number of items on the page (specified by the PageSize property).
You can further customize the appearance of the DataGrid control by programmatically adding attributes to the <td> and <tr> tags generated by the DataGrid control. Attributes can be inserted into the tags by providing a custom event handler for the ItemCreated or ItemDataBound event. In general, attributes are added in the event handler for the ItemCreated event. However, if the attributes depend on actual data, add the attributes in the handler for the ItemDataBound event.
To add an attribute to the <td> tag, first get the TableCell object that represents the cell in the DataGrid control to which you want to add the attribute. The Control.Controls collection for the Item property (DataGridItemEventArgs indexer) of the DataGridItemEventArgs passed into the event handler can be used to get the desired TableCell. You can then use the AttributeCollection.Add method of the Attributes collection for the TableCell to add attributes to the <td> tag.
To add an attribute to the <tr> tag, first get the DataGridItem that represents the row in the DataGrid control to which you want to add the attribute. The Item property (DataGridItemEventArgs indexer) of the DataGridItemEventArgs passed into the event handler can be used to get the desired DataGridItem. You can then use the AttributeCollection.Add method of the Attributes collection for the DataGridItem to add attributes to the <tr> tag.
Caution |
|---|
| Text is not HTML encoded before it is displayed in the DataGrid control. This makes it possible to embed script within HTML tags in the text. If the values for the control come from user input, be sure to validate the values to help prevent security vulnerabilities. |
For detailed information on the DataGrid Web server control's properties and events, see the DataGrid Class documentation.
The following example demonstrates how to use the DataGrid control to display the items in the data source.
The following example demonstrates how to use paging in a DataGrid control.
Typically, a data source that contains all the items in the list is loaded every time the DataGrid control displays a page of information. When the data source is very large, this can consume a lot of resources. Custom paging allows you to load just the segment of data needed to display the page.
To enable custom paging, set the AllowPaging property and AllowCustomPaging properties to true and provide code to handle the PageIndexChanged event. The typical logic for the PageIndexChanged event is to set the CurrentPageIndex property to the index of the page to display and then rebind the data source to the control. The index of the page to display is often accessed using the NewPageIndex property of the DataGridPageChangedEventArgs object passed to the event handler. Next, create a data source that contains the data to display on a single page. After the data source is created, use the DataBind method to bind the data source to the DataGrid control. Since only a segment of the data is loaded, set the VirtualItemCount property to the total number of items you want to display in the DataGrid control. This allows the control to determine the total number of pages needed for the paging controls.
When using custom paging, the DataGrid control assumes that the data source only contains the items to be displayed on the current page. All items in the data source up to the number of items specified by the PageSize property are displayed.
The following code example demonstrates how to use the AllowCustomPaging property to enable custom paging.
The DataGrid control also provides built-in sorting capabilities. When sorting is enabled, LinkButton controls are rendered in the header of each column that allow you to sort the DataGrid by the selected column. The SortCommand event is raised when a LinkButton is clicked. It is up to you to provide code for the event handler. The typical logic for the handler is to sort the list, and then rebind the data to the DataGrid.
The following example demonstrates how to use sorting in a DataGrid control.
Note
Caution