Share via


DataGrid Web Server Control

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 id="programmaticID"
     DataSource='<%# DataBindingExpression %>'
     AllowPaging="True|False"
     AllowSorting="True|False"
     AutoGenerateColumns="True|False"
     BackImageUrl="url"
     CellPadding="pixels"
     CellSpacing="pixels"
     DataKeyField="DataSourceKeyField"
     GridLines="None|Horizontal|Vertical|Both"
     HorizontalAlign="Center|Justify|Left|NotSet|Right"
     PagedDataSource
     PageSize="ItemCount"
     ShowFooter="True|False"
     ShowHeader="True|False"
     VirtualItemCount="ItemCount"
     OnCancelCommand="OnCancelCommandMethod"
     OnDeleteCommand="OnDeleteCommandMethod"
     OnEditCommand="OnEditCommandMethod"
     OnItemCommand="OnItemCommandMethod"
     OnItemCreated="OnItemCreatedMethod"
     OnPageIndexChanged="OnPageIndexChangedMethod"
     OnSortCommand="OnSortCommandMethod"
     OnUpdateCommand="OnUpdateCommandMethod"
     runat="server" >

   <AlternatingItemStyle ForeColor="Blue"/>
   <EditItemStyle BackColor="Yellow"/>
   <FooterStyle BorderColor="Gray"/>
   <HeaderStyle BorderColor="Gray"/>
   <ItemStyle Font-Bold="True"/>
   <PagerStyle Font-Name="Ariel"/>
   <SelectedItemStyle BackColor="Blue"/>

</asp:DataGrid>
or
<asp:DataGrid id="programmaticID"
     DataSource='<%# DataBindingExpression %>'
     AutoGenerateColumns="False"
     (other properties)
     runat="server" >

   <AlternatingItemStyle ForeColor="Blue"/>
   <EditItemStyle BackColor="Yellow"/>
   <FooterStyle BorderColor="Gray"/>
   <HeaderStyle BorderColor="Gray"/>
   <ItemStyle Font-Bold="True"/>
   <PagerStyle Font-Name="Ariel"/>
   <SelectedItemStyle BackColor="Blue"/>

   <Columns>
      <asp:BoundColumn
           DataField="DataSourceField"
           DataFormatString="FormatString"
           FooterText="FooterText"
           HeaderImageUrl="url"
           HeaderText="HeaderText"
           ReadOnly="True|False"
           SortExpression ="DataSourceFieldToSortBy"
           Visible="True|False"
           FooterStyle-property="value"
           HeaderStyle-property="value"
           ItemStyle-property="value"/>

      <asp:ButtonColumn
           ButtonType="LinkButton|PushButton"
           Command="BubbleText"
           DataTextField="DataSourceField"
           DataTextFormatString="FormatString"
           FooterText="FooterText"
           HeaderImageUrl="url"
           HeaderText="HeaderText"
           ReadOnly="True|False"
           SortExpression="DataSourceFieldToSortBy"
           Text="ButtonCaption"
           Visible="True|False"/>

      <asp:EditCommandColumn
           ButtonType="LinkButton|PushButton"
           CancelText="CancelButtonCaption"
           EditText="EditButtonCaption"
           FooterText="FooterText"
           HeaderImageUrl="url"
           HeaderText="HeaderText"
           ReadOnly="True|False"
           SortExpression="DataSourceFieldToSortBy"
           UpdateText="UpdateButtonCaption"
           Visible="True|False"/>

      <asp:HyperLinkColumn
           DataNavigateURLField="DataSourceField"
           DataNavigateURLFormatString="FormatExpression"
           DataTextField="DataSourceField"
           DataTextFormatString="FormatExpression"
           FooterText="FooterText"
           HeaderImageUrl="url"
           HeaderText="HeaderText"
           NavigateURL="url"
           ReadOnly="True|False"
           SortExpression="DataSourceFieldToSortBy"
           Target="window"
           Text="HyperLinkText"
           Visible="True|False"/>

      <asp:TemplateColumn
           FooterText="FooterText"
           HeaderImageUrl="url"
           HeaderText="HeaderText"
           ReadOnly="True|False"
           SortExpression="DataSourceFieldToSortBy"
           Visible="True|False">

         <HeaderTemplate>
            Header template HTML
         </HeaderTemplate >
         <ItemTemplate>
            ItemTemplate HTML
         </ItemTemplate>
         <EditItemTemplate>
            EditItem template HTML
         </EditItemTemplate>
         <FooterTemplate>
            Footer template HTML
         </FooterTemplate>

      </asp:TemplateColumn>
   </Columns>

</asp:DataGrid>

Remarks

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

DataGridColumn Base Properties

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

BoundColumn Properties

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 String.Format method.
ReadOnly true if the column cannot be edited when the row is put into edit mode; otherwise, false.

ButtonColumn Properties

Property Description
ButtonType The type of button to render. The default is LinkButton.

When programming, this property is set using the ButtonColumnType Enumeration.

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 e event 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.

TemplateColumn Properties

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.

HyperLinkColumn Properties

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.

EditCommandColumn Properties

Property Description
ButtonType The type of button to render. The default is LinkButton.

When programming, this property is set using the ButtonColumnType Enumeration.

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

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

Example

The following example demonstrates how to use the DataGrid control to display the items in the data source.

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
   <script runat="server">

      Function CreateDataSource() As ICollection

         Dim dt As New DataTable()
         Dim dr As DataRow
         Dim i As Integer
        
         dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
         dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
         dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
        
         For i = 0 To 8
            dr = dt.NewRow()
            
            dr(0) = i
            dr(1) = "Item " + i.ToString()
            dr(2) = 1.23 *(i + 1)
            
            dt.Rows.Add(dr)
         Next i
        
         Dim dv As New DataView(dt)
         Return dv

      End Function 'CreateDataSource

      Sub Page_Load(sender As Object, e As EventArgs)
        
         If Not IsPostBack Then
            ' Need to load this data only once.
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
         End If

      End Sub 'Page_Load
 
   </script>
 
<body>
 
   <form runat="server">
 
      <h3>DataGrid Example</h3>
 
      <b>Product List</b>
 
      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AutoGenerateColumns="true"
           runat="server">

         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle> 
 
      </asp:DataGrid>
 
   </form>
 
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<html>
<script runat="server">

   ICollection CreateDataSource() 
   {
      DataTable dt = new DataTable();
      DataRow dr;

      dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
      dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
      dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));

      for (int i = 0; i < 9; i++) 
      {
         dr = dt.NewRow();

         dr[0] = i;
         dr[1] = "Item " + i.ToString();
         dr[2] = 1.23 * (i + 1);

         dt.Rows.Add(dr);
      }

      DataView dv = new DataView(dt);
      return dv;
   }

   void Page_Load(Object sender, EventArgs e) 
   {

      if (!IsPostBack) 
      {
         // Need to load this data only once.
         ItemsGrid.DataSource= CreateDataSource();
         ItemsGrid.DataBind();
      }
   }

</script>

<body>

   <form runat="server">

      <h3>DataGrid Example</h3>

      <b>Product List</b>

      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           HeaderStyle-BackColor="#00aaaa"
           AutoGenerateColumns="true"
           runat="server">

      </asp:DataGrid>

   </form>

</body>
</html>

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

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>

   <script runat="server">
 
      Dim Cart As DataTable
      Dim CartView As DAtaView

      Function CreateDataSource() As ICollection

         Dim dt As New DataTable()
         Dim dr As DataRow
            
         dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
         dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
         dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
            
         Dim i As Integer
         For i = 0 To 99
            dr = dt.NewRow()
                
            dr(0) = i
            dr(1) = "Item " + i.ToString()
            dr(2) = 1.23 *(i + 1)
            dt.Rows.Add(dr)
         Next i
            
         Dim dv As New DataView(dt)
         Return dv

      End Function 'CreateDataSource

      Sub Page_Load(sender As Object, e As EventArgs)
            
         If Not IsPostBack Then
            ' Need to load this data only once.
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
         End If
            
         If CheckBox1.Checked Then
            ItemsGrid.PagerStyle.Mode = PagerMode.NumericPages
         Else
            ItemsGrid.PagerStyle.Mode = PagerMode.NextPrev
         End If 

      End Sub 'Page_Load

      Sub Grid_Change(sender As Object, e As DataGridPageChangedEventArgs)
            
         ' Set CurrentPageIndex to the page the user clicked.
         ItemsGrid.CurrentPageIndex = e.NewPageIndex
            
         ' Rebind the data. 
         ItemsGrid.DataSource = CreateDataSource()
         ItemsGrid.DataBind()

      End Sub 'Grid_Change  

</script>
 
<body>
 
   <form runat="server">

      <h3>DataGrid Paging Example</h3>
 
      <asp:DataGrid id="ItemsGrid" runat="server"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AllowPaging="true"
           AutoGenerateColumns="false"        
           OnPageIndexChanged="Grid_Change">
 
         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle>
  
         <PagerStyle Mode="NextPrev">
         </PagerStyle> 

         <Columns>

            <asp:BoundColumn 
                 HeaderText="Number" 
                 DataField="IntegerValue"/>
 
            <asp:BoundColumn 
                 HeaderText="Item" 
                 DataField="StringValue"/>

            <asp:BoundColumn 
                 HeaderText="Price" 
                 DataField="CurrencyValue" 
                 DataFormatString="{0:c}">
 
               <ItemStyle HorizontalAlign="right">
               </ItemStyle>
     
            </asp:BoundColumn>

         </Columns>

      </asp:DataGrid>

      <br>

      <asp:CheckBox id="CheckBox1" 
                    Text="Show page navigation"
                    AutoPostBack="true"
                    runat="server"/>
 
   </form>
 
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>

   <script runat="server">
 
      DataTable Cart;
      DataView CartView;
 
      ICollection CreateDataSource() 
      {
         DataTable dt = new DataTable();
         DataRow dr;
 
         dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
         dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
         dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
 
         for (int i = 0; i < 100; i++) 
         {
            dr = dt.NewRow();
 
            dr[0] = i;
            dr[1] = "Item " + i.ToString();
            dr[2] = 1.23 * (i+1); 
            dt.Rows.Add(dr);
         }
 
         DataView dv = new DataView(dt);
         return dv;
      }
 
      void Page_Load(Object sender, EventArgs e) 
      { 
 
         if (!IsPostBack) 
         {
            // Need to load this data only once.
            ItemsGrid.DataSource = CreateDataSource();
            ItemsGrid.DataBind();
         }
 
         if (CheckBox1.Checked)
            ItemsGrid.PagerStyle.Mode = PagerMode.NumericPages;
         else
            ItemsGrid.PagerStyle.Mode = PagerMode.NextPrev;

      }
 
      void Grid_Change(Object sender, DataGridPageChangedEventArgs e) 
      {
 
         // Set CurrentPageIndex to the page the user clicked.
         ItemsGrid.CurrentPageIndex = e.NewPageIndex;

         // Rebind the data. 
         ItemsGrid.DataSource = CreateDataSource();
         ItemsGrid.DataBind();
      
      }
 
   </script>
 
<body>
 
   <form runat="server">

      <h3>DataGrid Paging Example</h3>
 
      <asp:DataGrid id="ItemsGrid" runat="server"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AllowPaging="true"
           AutoGenerateColumns="false"        
           OnPageIndexChanged="Grid_Change">
 
         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle>
 
         <PagerStyle Mode="NextPrev">
         </PagerStyle> 

         <Columns>

            <asp:BoundColumn 
                 HeaderText="Number" 
                 DataField="IntegerValue"/>
   
            <asp:BoundColumn 
                 HeaderText="Item" 
                 DataField="StringValue"/>

            <asp:BoundColumn 
                 HeaderText="Price" 
                 DataField="CurrencyValue" 
                 DataFormatString="{0:c}">
 
               <ItemStyle HorizontalAlign="right">
               </ItemStyle>
     
            </asp:BoundColumn>

         </Columns>

      </asp:DataGrid>

      <br>

      <asp:CheckBox id="CheckBox1" 
                    Text="Show page navigation"
                    AutoPostBack="true"
                    runat="server"/>
 
   </form>
 
</body>
</html>

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 example demonstrates how to use custom paging in a DataGrid control.

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<html>
   <script runat="server">

      Dim start_index As Integer

      Function CreateDataSource() As ICollection
            
         Dim dt As New DataTable()
         Dim dr As DataRow
            
         dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
         dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
         dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
            
         Dim i As Integer
         For i = start_index To (start_index + ItemsGrid.PageSize) - 1
            dr = dt.NewRow()
                
            dr(0) = i
            dr(1) = "Item " + i.ToString()
            dr(2) = 1.23 *(i + 1)
                
            dt.Rows.Add(dr)
         Next i
           
         Dim dv As New DataView(dt)
         Return dv

      End Function 'CreateDataSource
        
      Sub Page_Load(sender As Object, e As EventArgs)
            
         If CheckBox1.Checked Then
            ItemsGrid.PagerStyle.Mode = PagerMode.NumericPages
         Else
            ItemsGrid.PagerStyle.Mode = PagerMode.NextPrev
         End If 

         If Not IsPostBack Then
            start_index = 0
            ItemsGrid.VirtualItemCount = 100
         End If
            
         BindGrid()

      End Sub 'Page_Load

      Sub Grid_Change(sender As Object, e As DataGridPageChangedEventArgs)
            
          ItemsGrid.CurrentPageIndex = e.NewPageIndex
          start_index = ItemsGrid.CurrentPageIndex * ItemsGrid.PageSize
          BindGrid()
 
      End Sub 'Grid_Change

      Sub BindGrid()
            
         ItemsGrid.DataSource = CreateDataSource()
         ItemsGrid.DataBind()

      End Sub 'BindGrid 

   </script>

<body>

   <form runat="server">

      <h3>DataGrid Custom Paging Example</h3>

      <asp:DataGrid id="ItemsGrid" runat="server"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AllowPaging="true"
           AllowCustomPaging="true"
           AutoGenerateColumns="false"
           OnPageIndexChanged="Grid_Change">

         <PagerStyle NextPageText="Forward"
                     PrevPageText="Back"
                     Position="Bottom"
                     PageButtonCount="5"
                     BackColor="#00aaaa">
         </PagerStyle>

         <AlternatingItemStyle BackColor="yellow">
         </AlternatingItemStyle>

         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle>

         <Columns>
      
            <asp:BoundColumn HeaderText="Number" 
                 DataField="IntegerValue"/>

            <asp:BoundColumn
                 HeaderText="Item" 
                 DataField="StringValue"/>

            <asp:BoundColumn 
                 HeaderText="Price" 
                 DataField="CurrencyValue" 
                 DataFormatString="{0:c}">

               <ItemStyle HorizontalAlign="right">
               </ItemStyle>
   
            </asp:BoundColumn>

         </Columns>
      
      </asp:DataGrid>

      <br>

      <asp:CheckBox id="CheckBox1" 
           Text = "Show page navigation"
           AutoPostBack="true"
           runat="server"/>

   </form>

</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<html>
   <script runat="server">

      int start_index;

      ICollection CreateDataSource() 
      {

         DataTable dt = new DataTable();
         DataRow dr;

         dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
         dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
         dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
 
         for (int i = start_index; i < start_index + ItemsGrid.PageSize; i++) 
         {
            dr = dt.NewRow();

            dr[0] = i;
            dr[1] = "Item " + i.ToString();
            dr[2] = 1.23 * (i+1);

            dt.Rows.Add(dr);
         }

         DataView dv = new DataView(dt);
         return dv;
      }

      void Page_Load(Object sender, EventArgs e) 
      {

         if (CheckBox1.Checked)
            ItemsGrid.PagerStyle.Mode=PagerMode.NumericPages;
         else
            ItemsGrid.PagerStyle.Mode=PagerMode.NextPrev;

         if (!IsPostBack)
         {
            start_index = 0; 
            ItemsGrid.VirtualItemCount=100; 
         }

         BindGrid();
      
      }

      void Grid_Change(Object sender, DataGridPageChangedEventArgs e) 
      {
       
         ItemsGrid.CurrentPageIndex = e.NewPageIndex;
         start_index = ItemsGrid.CurrentPageIndex * ItemsGrid.PageSize;
         BindGrid();
     
      }

      void BindGrid() 
      {

         ItemsGrid.DataSource=CreateDataSource();
         ItemsGrid.DataBind();
     
      }

   </script>

<body>

   <form runat="server">

      <h3>DataGrid Custom Paging Example</h3>

      <asp:DataGrid id="ItemsGrid" runat="server"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AllowPaging="true"
           AllowCustomPaging="true"
           AutoGenerateColumns="false"
           OnPageIndexChanged="Grid_Change">

         <PagerStyle NextPageText="Forward"
                     PrevPageText="Back"
                     Position="Bottom"
                     PageButtonCount="5"
                     BackColor="#00aaaa">
         </PagerStyle>

         <AlternatingItemStyle BackColor="yellow">
         </AlternatingItemStyle>

         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle>

         <Columns>
      
            <asp:BoundColumn HeaderText="Number" 
                 DataField="IntegerValue"/>

            <asp:BoundColumn
                 HeaderText="Item" 
                 DataField="StringValue"/>

            <asp:BoundColumn 
                 HeaderText="Price" 
                 DataField="CurrencyValue" 
                 DataFormatString="{0:c}">

               <ItemStyle HorizontalAlign="right">
               </ItemStyle>
   
            </asp:BoundColumn>

         </Columns>
      
      </asp:DataGrid>

      <br>

      <asp:CheckBox id="CheckBox1" 
           Text = "Show page navigation"
           AutoPostBack="true"
           runat="server"/>

   </form>

</body>
</html>

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.

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>
   <script runat="server">
    
      Dim SortExpression As String
 
      Function CreateDataSource() As ICollection

         Dim dt As New DataTable()
         Dim dr As DataRow
         Dim Rand_Num As New Random()
        
         dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
         dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
         dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))
        
         Dim i As Integer
         For i = 0 To 14
            dr = dt.NewRow()
            
            dr(0) = i
            dr(1) = "Item " & i.ToString()
            dr(2) = 1.23 * Rand_Num.Next(1, 15)
            
            dt.Rows.Add(dr)
         Next i
        
         Dim dv As New DataView(dt)
         dv.Sort = SortExpression
         Return dv

      End Function 'CreateDataSource

      Sub Page_Load(sender As Object, e As EventArgs)
        
         If Not IsPostBack Then
            
            If SortExpression = "" Then
               SortExpression = "IntegerValue"
            End If

            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()

         End If

      End Sub 'Page_Load

      Sub Sort_Grid(sender As Object, e As DataGridSortCommandEventArgs)
    
         SortExpression = e.SortExpression.ToString()
         ItemsGrid.DataSource = CreateDataSource()
         ItemsGrid.DataBind()

      End Sub 'Sort_Grid
 
   </script>
 
<body>
 
   <form runat="server">
 
      <h3>DataGrid Sorting Example</h3>
 
      <asp:DataGrid id="ItemsGrid" runat="server"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AllowSorting="true"
           OnSortCommand="Sort_Grid"
           HeaderStyle-BackColor="#00aaaa"
           AutoGenerateColumns="true"/>
 
   </form>
 
</body>
</html>
[C#]
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>
 
<html>

   <script runat="server">
    
      string SortExpression;
 
      ICollection CreateDataSource() 
      {
         DataTable dt = new DataTable();
         DataRow dr;
         Random Rand_Num = new Random();
 
         dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
         dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
         dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
 
         for (int i = 0; i < 15; i++) 
         {
            dr = dt.NewRow();
   
            dr[0] = i;
            dr[1] = "Item " + i.ToString();
            dr[2] = 1.23 * Rand_Num.Next(1, 15);
 
            dt.Rows.Add(dr);
         }
 
         DataView dv = new DataView(dt);
         dv.Sort=SortExpression;
         return dv;
      }
 
      void Page_Load(Object sender, EventArgs e) 
      {
         if (!IsPostBack) 
         {
 
            if (SortExpression == "")
               SortExpression = "IntegerValue";      
            ItemsGrid.DataSource = CreateDataSource();
            ItemsGrid.DataBind();
         }
      }
 
      void Sort_Grid(Object sender, DataGridSortCommandEventArgs e) 
      {
         SortExpression = e.SortExpression.ToString();
         ItemsGrid.DataSource = CreateDataSource();
         ItemsGrid.DataBind();
      }
 
   </script>
 
<body>
 
   <form runat="server">
 
      <h3>DataGrid Sorting Example</h3>
 
      <asp:DataGrid id="ItemsGrid" runat="server"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AllowSorting="true"
           OnSortCommand="Sort_Grid"
           HeaderStyle-BackColor="#00aaaa"
           AutoGenerateColumns="true"/>
 
   </form>
 
</body>
</html>

See Also

Web Server Controls | DataGrid Class