DataGrid Web Server Control Declarative Syntax

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

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

EditCommandColumn

Encapsulates the most common edit commands (Edit, Update, Cancel) in a predefined column type.

HyperLinkColumn

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.

BoundColumn

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.

ButtonColumn

Creates a column that contains a user defined command button, such as Add or Remove, for each item in the column.

TemplateColumn

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

FooterText

Text to display on the lower edge of the column.

HeaderImageUrl

The URL of an image that is rendered in place of HeaderText text in the column header.

HeaderText

Text to display on the upper edge of the column.

Owner

A reference to the DataGrid control to which the bound column belongs (read-only).

This property is used only when programming.

SortExpression

The name of the field to sort the data source by when the user specifies sorting by the contents of this column.

Visible

true if the column is displayed; otherwise, false.

Property

Description

DataField

The field or property of the object in DataSource that is the source of data for the column.

DataFormatString

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.

ReadOnly

true if the column cannot be edited when the row is put into edit mode; otherwise, false.

Property

Description

ButtonType

The type of button to render. The default is LinkButton.

When programming, this property is set using the ButtonColumnType.

CommandName

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 eevent argument object.

The DataGrid control recognizes certain standard command names. These command names include Select, Sort, Update, Cancel, Edit, Delete, and Page.

DataTextField

The field name from the DataSource that is bound to the Text property of the button in the ButtonColumn.

DataTextFormatString

A formatting expression string that specifies how the field is displayed in the cell.

Text

The caption to display on the face of the button in this column. If DataTextField is set, it overrides this value.

Property

Description

EditItemTemplate

The HTML elements and controls that define the column when it is in edit mode.

FooterTemplate

The HTML elements and controls that define the column footer.

HeaderTemplate

The HTML elements and controls that define the column header.

ItemTemplate

The HTML elements and controls that define the column when it is displayed.

Property

Description

DataNavigateUrlField

The field or property of the object in DataSource that provides the URL of the page to move to.

DataNavigateUrlFormatString

A format expression to be used with the Text property.

DataTextField

The field or property of the object in DataSource that is the source of data for the Text property of the columns.

DataTextFormatString

The formatting string that specifies how the Text property is displayed in the control.

NavigateUrl

The URL of the page to move to. If DataNavigateUrlField is set, it overrides this property.

Target

The target window that displays the page. This can be the name of a window or a frame reference such as _TOP.

Text

The text of the hyperlink.

Property

Description

ButtonType

The type of button to render. The default is LinkButton.

When programming, this property is set using the ButtonColumnType.

EditText

The string to display on the face of the Edit button.

UpdateText

The string to display on the face of the Update button.

CancelText

The string to display on the face of the Cancel button.

You can customize the appearance of the DataGridcontrol 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

AlternatingItemStyle

The style of every other item (alternating items).

TableItemStyle

EditItemStyle

The style of the item being edited.

TableItemStyle

FooterStyle

The style of the footer at the end of the list (if any).

TableItemStyle

HeaderStyle

The style of the header at the beginning of the list (if any).

TableItemStyle

ItemStyle

The style of individual items.

Style

PagerStyle

The style of the page selection controls.

DataGridPagerStyle

SelectedItemStyle

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

No code example is currently available or this language may not be supported.

The following example demonstrates how to use paging in a DataGrid control.

No code example is currently available or this language may not be supported.
No code example is currently available or this language may not be supported.

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.

No code example is currently available or this language may not be supported.

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.

No code example is currently available or this language may not be supported.
No code example is currently available or this language may not be supported.
Show: