Share via


DataGrid controle de servidor Web Declarative sintaxe

The DataGrid controle processa dados tabulares,-limite grade. Este controle permite que você defina vários tipos de colunas para controlar o layout do Sumário da célula da grade (colunas acopladas, colunas de modelo) e adicionar funcionalidade específica (sistema autônomo edição botão colunas, colunas de hiperlink e assim por diante). O controle também suporta uma variedade de opções de paginação por meio de dados.

<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
                    DatahrefField="string"
                    DatahrefFormatString="string"
                    DataTextField="string"
                    DataTextFormatString="string"
                    FooterText="string"
                    HeaderImageUrl="uri"
                    HeaderText="string"
                    href="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>

Comentários

Antes de usar o DataGrid controlar, considere usar o GridView controle em vez disso. The GridView controle é nova no .NET estrutura versão 2.0 e é o sucessor do DataGrid controle.

The DataGrid controle exibe sistema autônomo campos de uma fonte de dados sistema autônomo colunas em uma tabela. Cada linha no DataGrid controle representa um registro na fonte de dados. The DataGrid controle dá suporte à seleção, edição, exclusão, paginação e classificação.

Por padrão, a AutoGenerateColumns propriedade é conjunto para true, que cria um BoundColumn objeto para cada campo na fonte de dados. Cada campo, em seguida, é processado sistema autônomo uma coluna no DataGrid controle na ordem em que cada campo é exibido na fonte de dados.

Você pode controlar manualmente as colunas que aparecem no DataGrid controle definindo a AutoGenerateColumns propriedade para false e, em seguida, listando as colunas que você deseja incluir entre abertura e fechamento <Columns> Rótulos de formatação. As colunas especificadas são adicionadas ao Columns coleção na ordem listada. Isso permite que você controle programático de colunas da DataGrid controle.

ObservaçãoObservação:

A ordem em que as colunas são exibidas na DataGrid controle é controlada pela ordem em que as colunas aparecem na Columns coleção. Embora você possa alterar programaticamente a ordem das colunas manipulando o Columns coleção, é mais fácil listar as colunas da ordem de exibição desejado.

ObservaçãoObservação:

Colunas explicitamente declaradas podem ser usadas em conjunto com as colunas geradas automaticamente. Quando usar ambos, declarados explicitamente colunas será processado primeiro, seguida por colunas geradas automaticamente. Colunas geradas automaticamente não são adicionadas ao Columns coleção.

Tipos de coluna diferente determinam o comportamento das colunas no controle. The DataGrid controle permite que você usar os seguintes tipos de colunas.

Tipo de coluna

Descrição

EditCommandColumn

Encapsula os comandos mais comuns de edição (Edit, Update, Cancel) em um tipo de coluna predefinidos.

HyperLinkColumn

Cria uma coluna com um conjunto de hiperlinks limite como o valor de um campo de dados. Por exemplo, uma grade que exibe uma lista de pedidos pode incluir uma coluna de hiperlink no qual o OrderID campo é processado sistema autônomo um hiperlink para uma página que exibe sistema autônomo detalhes da ordem.

BoundColumn

Cria uma coluna limite a um campo na fonte de dados e processados em uma célula de tabela usando estilos. Este é o tipo de coluna padrão para o DataGrid controle.

ButtonColumn

Cria uma coluna que contém um botão de comando definido pelo usuário, sistema autônomo Add ou Remove, para cada item na coluna.

TemplateColumn

Cria uma coluna que lhe permite definir o layout de controles usando modelos para elementos personalizados de HTML e controles.

As tabelas a seguir fornecem informações sobre as colunas que você pode declarar o DataGrid controle.

Propriedades Base DataGridColumn

As seguintes propriedades estão disponível em todos os DataGrid tipos de coluna.

Propriedade

Descrição

FooterText

Texto exibido na borda inferior da coluna.

HeaderImageUrl

A URL de uma imagem é processada no lugar de HeaderText texto no cabeçalho da coluna.

HeaderText

Texto exibido na borda superior da coluna.

Owner

Uma referência para o DataGrid controle ao qual a coluna acoplada pertence (somente leitura).

Esta propriedade é usada quando estiver programando.

SortExpression

O nome do campo para classificar a fonte de dados por quando o usuário Especifica a classificação pelo Sumário da coluna.

Visible

true Se a coluna é exibida; caso contrário, false.

Propriedades BoundColumn

Propriedade

Descrição

DataField

O campo ou propriedade do objeto em DataSource que é a fonte de dados da coluna.

DataFormatString

Uma seqüência de expressão de formatação que especifica como o campo é exibido na célula. Isso é semelhante à formatação expressões usadas pelo Format método.

ReadOnly

true Se a coluna não pode ser editada quando a linha é colocar em modo de edição; caso contrário, false.

Propriedades ButtonColumn

Propriedade

Descrição

ButtonType

O tipo de botão para processar. O padrão é LinkButton.

Quando estiver programando, essa propriedade é conjunto usando o ButtonColumnType.

CommandName

Uma seqüência de caracteres que indica o comando é enviado quando um botão na coluna for clicado. This string is available in the event-handling method through the CommandSource property of the eevent argument object.

The DataGrid controle reconhece certos nomes de comando padrão. Esses nomes de comando incluem Select, Sort, Update, Cancel, Edit, Delete, e Page.

DataTextField

O nome de campo do DataSource que está limite a Text propriedade do botão na ButtonColumn.

DataTextFormatString

Uma seqüência de expressão de formatação que especifica como o campo é exibido na célula.

Text

A legenda a ser exibida na face de botão nesta coluna. If DataTextField é definido, que ela substituirá esse valor.

Propriedades TemplateColumn

Propriedade

Descrição

EditItemTemplate

Os elementos HTML e controles que definem a coluna quando no modo de edição.

FooterTemplate

Os elementos HTML e controles que definem o rodapé da coluna.

HeaderTemplate

Os elementos HTML e controles que definem o cabeçalho da coluna.

ItemTemplate

Os elementos HTML e controles que definem a coluna quando ela é exibida.

Propriedades HyperLinkColumn

Propriedade

Descrição

DatahrefField

O campo ou propriedade do objeto em DataSource que fornece a URL da página para mover para.

DatahrefFormatString

Uma expressão de formato a ser usado com o Text propriedade.

DataTextField

O campo ou propriedade do objeto em DataSource Isto é a fonte de dados para o Text propriedade das colunas.

DataTextFormatString

A seqüência de caracteres de formatação que especifica como a Text propriedade é exibida no controle.

href

A URL da página para mover para. If DatahrefField é conjunto, ela prevalece sobre essa propriedade.

Target

A janela de destino que exibe a página. Isso pode ser o nome de uma janela ou um referência de quadro, sistema autônomo _TOP.

Text

O texto do hiperlink.

Propriedades EditCommandColumn

Propriedade

Descrição

ButtonType

O tipo de botão para processar. O padrão é LinkButton.

Quando estiver programando, essa propriedade é conjunto usando o ButtonColumnType.

EditText

A cadeia de caracteres a ser exibida na face do Edit botão.

UpdateText

A cadeia de caracteres a ser exibida na face do Update botão.

CancelText

A cadeia de caracteres a ser exibida na face do Cancel botão.

You can customize the appearance of the DataGridcontrol by setting the style properties of the different parts of the control. A tabela a seguir lista as propriedades de estilo para diferentes partes do DataGrid controle.

Propriedades de estilo

Propriedade de estilo

Descrição

Classe de estilo

AlternatingItemStyle

O estilo de todos os outros itens (itens alternados).

TableItemStyle

EditItemStyle

O estilo do item que está sendo editado.

TableItemStyle

FooterStyle

O estilo do rodapé no participante da lista (se houver).

TableItemStyle

HeaderStyle

O estilo do cabeçalho no início da lista (se houver).

TableItemStyle

ItemStyle

O estilo dos itens individuais.

Style

PagerStyle

O estilo dos controles de seleção de página.

DataGridPagerStyle

SelectedItemStyle

O estilo do item atualmente selecionado.

TableItemStyle

Para obter informações sobre as propriedades com suporte para cada classe de estilo, consulte Propriedades do objeto de estilo.

The DataGrid o controle contém funcionalidade interna para exibir seu Sumário em segmentos de página. O número de itens na página é determinado pelo PageSize propriedade. Se nenhum valor for especificado para o PageSize propriedade, o DataGrid controle exibe dez itens na página por vez.

Por padrão, a paginação está desabilitado. Para ativar a paginação, defina o AllowPaging propriedade para true e fornecer código para manipular o PageIndexChanged evento. A lógica comum para o PageIndexChanged evento é conjunto o CurrentPageIndex propriedade para o índice da página para exibir e, em seguida, vincular novamente a fonte de dados para o controle. O índice da página para exibir é freqüentemente acessado usando o NewPageIndex propriedade das DataGridPageChangedEventArgs objeto passado para o manipulador de eventos.

Com a paginação padrão, a DataGrid controle assume que a fonte de dados contém todos os itens a serem exibidos. The DataGrid controle calcula os índices dos itens na página corrente com base no índice de página (especificado pela CurrentPageIndex propriedade) e o número de itens na página (especificado pela PageSize propriedade).

Você pode personalizar ainda mais a aparência do DataGrid controle programaticamente adicionando atributos para o <td> e <tr> Rótulos geradas pela DataGrid controle. Atributos podem ser inseridos as Rótulos, fornecendo um personalizado manipulador de eventos o ItemCreated ou ItemDataBound evento. Em geral, os atributos são adicionados no manipulador de eventos o ItemCreated evento. No entanto, se os atributos dependem de dados real, adicionar os atributos no manipulador para o ItemDataBound evento.

Para adicionar um atributo à <td> marca, primeiro obter os TableCell objeto que representa a célula a DataGrid controle ao qual você deseja adicionar o atributo. The Control.Controls coleção para o Item propriedade)DataGridItemEventArgs indexador) dos DataGridItemEventArgs passado para o manipulador de eventos pode ser usado para obter o desejado TableCell. Você pode usar o AttributeCollection.Add método para o Attributes coleção para o TableCell Para adicionar atributos para o <td> marca.

Para adicionar um atributo à <tr> Inserir marcas de formatação, primeiro obter os DataGridItem na linha que representa o DataGrid controle ao qual você deseja adicionar o atributo. The Item propriedade)DataGridItemEventArgs indexador) dos DataGridItemEventArgs passado no evento de manipulador pode ser usado para obter o desejado DataGridItem. Você pode usar o AttributeCollection.Add método para o Attributes coleção para o DataGridItem Para adicionar atributos para o <tr> marca.

Aviso

O texto não é codificado antes que seja exibido em HTML a Controle DataGrid Isso torna possível incorporar o script nas Rótulos HTML no texto. Se os valores para o controle provenientes da entrada do usuário, certifique-se de validar os valores para ajudar a evitar vulnerabilidades de segurança.

Para obter informações detalhadas sobre o DataGrid Propriedades e eventos de controle de servidor de Web, consulte o DataGrid Documentação da classe.

Exemplo

O exemplo a seguir demonstra como usar o DataGrid controle para exibir os itens na fonte de dados.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
   <script language="VB" runat="server">
     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 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
            ' Load this data only once.
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
        End If
    End Sub 'Page_Load

  </script>

<head runat="server">
    <title>DataGrid Example</title>
</head>
<body>

   <form id="form1" 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>
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
   <script language="C#" 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) 
         {
            // Load this data only once.
            ItemsGrid.DataSource= CreateDataSource();
            ItemsGrid.DataBind();
         }
      }

   </script>

<head runat="server">
    <title>DataGrid Example</title>
</head>
<body>

   <form id="form1" 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>

O exemplo a seguir demonstra como usar paginação em um DataGrid controle.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<script language="VB" 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>

<head runat="server">
    <title>DataGrid Paging Example</title>
</head>
<body>

   <form id="form1" 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>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<script language="C#" 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>

<head runat="server">
    <title>DataGrid Paging Example</title>
</head>
<body>

   <form id="form1" 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>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<script language="JScript" runat="server">

   var Cart : DataTable;
   var CartView : DataView;

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

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

      for (var i : int = 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);
      }

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

   function Page_Load(sender, e : EventArgs) 
   {

      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;

   }

   function Grid_Change(sender, e : DataGridPageChangedEventArgs) 
   {

      // Set CurrentPageIndex to the page the user clicked.
      ItemsGrid.CurrentPageIndex = e.NewPageIndex;

      // Rebind the data. 
      ItemsGrid.DataSource = CreateDataSource();
      ItemsGrid.DataBind();

   }


</script>

<head runat="server">
    <title>DataGrid Paging Example</title>
</head>
<body>

   <form id="form1" 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>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    Function CreateDataSource() As ICollection
        ' Create sample data for the DataGrid control.
        Dim dt As DataTable = New DataTable()
        Dim dr As DataRow

        ' Define the columns of the table.
        dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
        dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
        dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))

        ' Populate the table with sample values.
        Dim i As Integer
        For i = 0 To 100
            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 DataView = New DataView(dt)
        Return dv
    End Function

    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        ' Load sample data only once, when the page is first loaded.
        If Not IsPostBack Then
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
        End If
    End Sub

    Sub Check_Change(ByVal sender As Object, ByVal e As EventArgs)
        ' Allow or prevent paging depending on the user's selection.
        ItemsGrid.AllowPaging = AllowPagingCheckBox.Checked()

        ' Rebind the data to refresh the DataGrid control. 
        ItemsGrid.DataSource = CreateDataSource()
        ItemsGrid.DataBind()
    End Sub

    Sub Grid_Change(ByVal sender As Object, ByVal e As DataGridPageChangedEventArgs)
        ' For the DataGrid control to navigate to the correct page when
        ' paging is allowed, the CurrentPageIndex property must be updated
        ' programmatically. This process is usually accomplished in the
        ' event-handling method for the PageIndexChanged event.

        ' Set CurrentPageIndex to the page the user clicked.
        ItemsGrid.CurrentPageIndex = e.NewPageIndex

        ' Rebind the data to refresh the DataGrid control. 
        ItemsGrid.DataSource = CreateDataSource()
        ItemsGrid.DataBind()
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head2" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <h3>DataGrid AllowPaging Example</h3>

    <p>Select whether to allow paging in the DataGrid control.<br />
       <asp:CheckBox id="AllowPagingCheckBox"
            Text="Allow paging"
            AutoPostBack="True"
            Checked="True"
            OnCheckedChanged="Check_Change"
            runat="server" />
    </p>
    <hr />
    <asp:Label ID="Label1" runat="server" 
        AssociatedControlID="ItemsGrid" 
        Font-Bold="true">Product List</asp:Label>
    <asp:DataGrid id="ItemsGrid" runat="server"
        BorderColor="Gray"
        BorderWidth="1"
        CellPadding="3"
        UseAccessibleHeader="true"
        AutoGenerateColumns="False"
        PageSize="10"
        AllowPaging="True"
        OnPageIndexChanged="Grid_Change">

        <HeaderStyle BackColor="LightBlue" />
        <Columns>
            <asp:BoundColumn DataField="IntegerValue" 
                 SortExpression="IntegerValue"
                 ItemStyle-HorizontalAlign="center"
                 HeaderText="Item" />

            <asp:BoundColumn DataField="StringValue" 
                HeaderText="Description" 
                ItemStyle-HorizontalAlign="left"
                SortExpression="StringValue" />

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

        </Columns>
        <ItemStyle HorizontalAlign="Right" />
    </asp:DataGrid>

    </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    private ICollection CreateDataSource()
    {
        // Create sample data for the DataGrid control.
        DataTable dt = new DataTable();
        DataRow dr;

        // Define the columns of the table.
        dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
        dt.Columns.Add(new DataColumn("StringValue", typeof(String)));
        dt.Columns.Add(new DataColumn("CurrencyValue", typeof(Double)));

        // Populate the table with sample values.
        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;
    }

    private void Page_Load(Object sender, EventArgs e)
    { 
        // Load sample data only once, when the page is first loaded.
        if (!IsPostBack)
        { 
            ItemsGrid.DataSource = CreateDataSource();
            ItemsGrid.DataBind();
        }
    }

    private void Check_Change(Object sender, EventArgs e)
    {
        // Allow or prevent paging depending 
        // on the user's selection.
        ItemsGrid.AllowPaging = AllowPagingCheckBox.Checked;

        // Rebind the data to refresh the DataGrid control. 
        ItemsGrid.DataSource = CreateDataSource();
        ItemsGrid.DataBind();
    }

    private void Grid_Change(Object sender, DataGridPageChangedEventArgs e) 
    {
        // For the DataGrid control to navigate to the correct page when
        // paging is allowed, the CurrentPageIndex property must be updated
        // programmatically. This process is usually accomplished in the
        // event-handling method for the PageIndexChanged event.

        // Set CurrentPageIndex to the page the user clicked.
        ItemsGrid.CurrentPageIndex = e.NewPageIndex;

        // Rebind the data to refresh the DataGrid control. 
        ItemsGrid.DataSource = CreateDataSource();
        ItemsGrid.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>DataGrid AllowPaging Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <h3>DataGrid AllowPaging Example</h3>

    <p>Select whether to allow paging in the DataGrid control.<br />
       <asp:CheckBox id="AllowPagingCheckBox"
            Text="Allow paging"
            AutoPostBack="True"
            Checked="True"
            OnCheckedChanged="Check_Change"
            runat="server" />
    </p>
    <hr />
    <asp:Label runat="server" 
        AssociatedControlID="ItemsGrid" 
        Font-Bold="true">Product List</asp:Label>
    <asp:DataGrid id="ItemsGrid" runat="server"
        BorderColor="Gray"
        BorderWidth="1"
        CellPadding="3"
        AutoGenerateColumns="False"
        UseAccessibleHeader="true"
        PageSize="10"
        AllowPaging="True"
        OnPageIndexChanged="Grid_Change">

        <HeaderStyle BackColor="LightBlue" />
        <Columns>
            <asp:BoundColumn DataField="IntegerValue" 
                 SortExpression="IntegerValue"
                 ItemStyle-HorizontalAlign="center"
                 HeaderText="Item" />

            <asp:BoundColumn DataField="StringValue" 
                HeaderText="Description" 
                ItemStyle-HorizontalAlign="left"
                SortExpression="StringValue" />

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

        </Columns>
        <ItemStyle HorizontalAlign="Right" />
    </asp:DataGrid>

    </div>
    </form>
</body>
</html>

Normalmente, uma fonte de dados que contém todos os itens na lista é carregada sempre o DataGrid controle exibe uma página de informações. Quando a fonte de dados é muito grande, isso pode consumir muitos recursos. Paginação personalizada permite que você carregue apenas o segmento de dados necessários para exibir a página.

Para ativar a paginação personalizada, conjunto o AllowPaging propriedade e AllowCustomPaging propriedades para true e fornecer código para manipular o PageIndexChanged evento. A lógica comum para o PageIndexChanged evento é conjunto o CurrentPageIndex propriedade para o índice da página para exibir e, em seguida, vincular novamente a fonte de dados para o controle. O índice da página para exibir é freqüentemente acessado usando o NewPageIndex propriedade das DataGridPageChangedEventArgs objeto passado para o manipulador de eventos. Em seguida, crie uma fonte de dados que contém os dados a serem exibidos em uma única página. Após a fonte de dados é criada, usar o DataBind método para BIND a fonte de dados para o DataGrid controle. Como apenas um segmento de dados é carregado, conjunto o VirtualItemCount propriedade para o número total de itens que você deseja exibir na DataGrid controle. Isso permite que o controle determinar o número total de páginas necessário para os controles de paginação.

Ao usar paginação personalizada, a DataGrid controle assume que a fonte de dados contém apenas os itens a serem exibidos na página corrente. Todos os itens na fonte de dados a ser o número de itens especificados pelo PageSize propriedade são exibidos.

O exemplo de código a seguir demonstra como usar o AllowCustomPaging propriedade para ativar a paginação personalizada.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

   <script runat="server">

      ' Normally, an entire data source is loaded in the DataGrid control, 
      ' which can take up a lot of resources. This example uses custom 
      ' paging, which loads only the segment of data needed to fill a
      ' single page. In order to query for the appropriate segment of
      ' data, the index of the first item displayed on a page must be
      ' tracked as the user navigates between pages.
      Dim startIndex As Integer = 0

      Function CreateDataSource() As ICollection 

         ' Create sample data for the DataGrid control.
         Dim dt As DataTable = New DataTable()
         Dim dr As DataRow

         ' Define the columns of the table.
         dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
         dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
         dt.Columns.Add(New DataColumn("DateTimeValue", GetType(String)))
         dt.Columns.Add(New DataColumn("BoolValue", GetType(Boolean)))

         ' Populate the table with sample values. When using custom paging,
         ' a query should only return enough data to fill a single page, 
         ' beginning at the start index.
         Dim i As Integer         

         For i = startIndex To ((startIndex + MyDataGrid.PageSize) - 1) 

             dr = dt.NewRow()

             dr(0) = i
             dr(1) = "Item " & i.ToString()
             dr(2) = DateTime.Now.ToShortDateString()
             If (i Mod 2 <> 0) Then
                dr(3) = True
             Else
                dr(3) = False
             End If

             dt.Rows.Add(dr)

         Next i

         Dim dv As DataView = New DataView(dt)
         Return dv

      End Function

      Sub Page_Load(sender As Object, e As EventArgs) 

         ' Load sample data only once, when the page is first loaded.
         If Not IsPostBack Then 

            ' Set the virtual item count, which specifies the total number
            ' items displayed in the DataGrid control when custom paging
            ' is used.
            MyDataGrid.VirtualItemCount = 200

            ' Retrieve the segment of data to display on the page from the 
            ' data source and bind it to the DataGrid control.
            BindGrid()

         End If

      End Sub

      Sub MyDataGrid_Page(sender as Object, e As DataGridPageChangedEventArgs) 

         ' For the DataGrid control to navigate to the correct page when
         ' paging is allowed, the CurrentPageIndex property must be updated
         ' programmatically. This process is usually accomplished in the
         ' event-handling method for the PageIndexChanged event.

         ' Set CurrentPageIndex to the page the user clicked.
         MyDataGrid.CurrentPageIndex = e.NewPageIndex

         ' Calculate the index of the first item to display on the page 
         ' using the current page index and the page size.
         startIndex = MyDataGrid.CurrentPageIndex * MyDataGrid.PageSize

         ' Retrieve the segment of data to display on the page from the 
         ' data source and bind it to the DataGrid control.
         BindGrid()

      End Sub

      Sub BindGrid() 

         MyDataGrid.DataSource = CreateDataSource()
         MyDataGrid.DataBind()

      End Sub

   </script>

<head runat="server">
    <title> DataGrid Custom Paging Example </title>
</head>
<body>

   <form id="form1" runat="server">

      <h3> DataGrid Custom Paging Example </h3>

      <asp:DataGrid id="MyDataGrid" 
           AllowCustomPaging="True" 
           AllowPaging="True" 
           PageSize="10" 
           OnPageIndexChanged="MyDataGrid_Page" 
           runat="server">

         <HeaderStyle BackColor="Navy" 
                      ForeColor="White" 
                      Font-Bold="True" />

         <PagerStyle Mode="NumericPages" 
                     HorizontalAlign="Right" />

      </asp:DataGrid>

   </form>

</body>
</html>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >

   <script runat="server">

      // Normally, an entire data source is loaded in the DataGrid control, 
      // which can take up a lot of resources. This example uses custom 
      // paging, which loads only the segment of data needed to fill a
      // single page. In order to query for the appropriate segment of
      // data, the index of the first item displayed on a page must be
      // tracked as the user navigates between pages.
      int startIndex = 0;

      ICollection CreateDataSource() 
      {

         // Create sample data for the DataGrid control.
         DataTable dt = new DataTable();
         DataRow dr;

         // Define the columns of the table.
         dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
         dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
         dt.Columns.Add(new DataColumn("DateTimeValue", typeof(string)));
         dt.Columns.Add(new DataColumn("BoolValue", typeof(bool)));

         // Populate the table with sample values. When using custom paging,
         // a query should only return enough data to fill a single page, 
         // beginning at the start index.
         for (int i = startIndex; i < (startIndex + MyDataGrid.PageSize); i++) 
         {
             dr = dt.NewRow();

             dr[0] = i;
             dr[1] = "Item " + i.ToString();
             dr[2] = DateTime.Now.ToShortDateString();
             dr[3] = (i % 2 != 0) ? true : false;

             dt.Rows.Add(dr);
         }

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

      }

      void Page_Load(Object sender, EventArgs e) 
      {

         // Load sample data only once, when the page is first loaded.
         if (!IsPostBack) 
         {

            // Set the virtual item count, which specifies the total number
            // items displayed in the DataGrid control when custom paging
            // is used.
            MyDataGrid.VirtualItemCount = 200;

            // Retrieve the segment of data to display on the page from the
            // data source and bind it to the DataGrid control.
            BindGrid();

         }

      }

      void MyDataGrid_Page(Object sender, DataGridPageChangedEventArgs e) 
      {

         // For the DataGrid control to navigate to the correct page when
         // paging is allowed, the CurrentPageIndex property must be updated
         // programmatically. This process is usually accomplished in the
         // event-handling method for the PageIndexChanged event.

         // Set CurrentPageIndex to the page the user clicked.
         MyDataGrid.CurrentPageIndex = e.NewPageIndex;

         // Calculate the index of the first item to display on the page 
         // using the current page index and the page size.
         startIndex = MyDataGrid.CurrentPageIndex * MyDataGrid.PageSize;

         // Retrieve the segment of data to display on the page from the 
         // data source and bind it to the DataGrid control.
         BindGrid();

      }

      void BindGrid() 
      {

         MyDataGrid.DataSource = CreateDataSource();
         MyDataGrid.DataBind();

      }

   </script>

<head runat="server">
    <title> DataGrid Custom Paging Example </title>
</head>
<body>

   <form id="form1" runat="server">

      <h3> DataGrid Custom Paging Example </h3>

      <asp:DataGrid id="MyDataGrid" 
           AllowCustomPaging="True" 
           AllowPaging="True" 
           PageSize="10" 
           OnPageIndexChanged="MyDataGrid_Page" 
           runat="server">

         <HeaderStyle BackColor="Navy" 
                      ForeColor="White" 
                      Font-Bold="True" />

         <PagerStyle Mode="NumericPages" 
                     HorizontalAlign="Right" />

      </asp:DataGrid>

   </form>

</body>
</html>

The DataGrid controle também fornece recursos internos de classificação. Quando a classificação está ativada, LinkButton controles são processados no cabeçalho de cada coluna que permitem a você classificar o DataGrid Por que a coluna selecionada. The SortCommand evento é disparado quando um LinkButton é clicado. Ele é fornecer código para o manipulador de eventos. A lógica típica para o manipulador é classificar a lista e, em seguida, vincular novamente os dados para o DataGrid.

O exemplo a seguir demonstra como usar a classificação em um DataGrid controle.

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

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
 <script language="VB" 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>

 <head runat="server">
    <title>DataGrid Sorting Example</title>
</head>
<body>

    <form id="form1" 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>

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

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
 <script language="C#" 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>

 <head runat="server">
    <title>DataGrid Sorting Example</title>
</head>
<body>

    <form id="form1" 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>

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

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
 <script language="JScript" runat="server">

    var SortExpression : String;

    function CreateDataSource () : ICollection
    {
      var dt : DataTable = new DataTable();
      var dr : DataRow;
      var Rand_Num : Random = new Random();

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

      for (var i : int = 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);
      }

      var dv : DataView = new DataView(dt);
      dv.Sort=SortExpression;
      return dv;
    }

    function Page_Load(sender, e : EventArgs) 
    {

       if (!IsPostBack) 
       {

          if (SortExpression == "")
             SortExpression = "IntegerValue";      
          ItemsGrid.DataSource = CreateDataSource();
          ItemsGrid.DataBind();
       }

    }

    function Sort_Grid(sender, e : DataGridSortCommandEventArgs) 
    {
       SortExpression = e.SortExpression.ToString();
       ItemsGrid.DataSource = CreateDataSource();
       ItemsGrid.DataBind();
    }

 </script>

 <head runat="server">
    <title>DataGrid Sorting Example</title>
</head>
<body>

    <form id="form1" 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>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    Function CreateDataSource() As ICollection
        ' Create a Random object to mix up the order 
        ' of items in the sample data.
        Dim randNum As Random = New Random()

        ' Create sample data for the DataGrid control.
        Dim dt As DataTable = New DataTable()

        ' Define the columns of the table.
        dt.Columns.Add( _
            New DataColumn("IntegerValue", GetType(Int32)))
        dt.Columns.Add( _
            New DataColumn("StringValue", GetType(String)))
        dt.Columns.Add( _
            New DataColumn("CurrencyValue", GetType(Double)))

        ' Populate the table with sample values.
        Dim i As Integer
        For i = 0 To 8
            Dim dr As DataRow = dt.NewRow()
            dr(0) = i
            dr(1) = "Item " & randNum.Next(1, 15).ToString()
            dr(2) = 1.23 * randNum.Next(1, 15)
            dt.Rows.Add(dr)
        Next

        ' Persist the data source between posts to 
        ' the server, in the session state.  
        Session("Source") = dt

        Dim dv As DataView = New DataView(dt)
        Return dv
    End Function

    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        ' Load sample data when the page is first loaded.
        If Not IsPostBack Then
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
        End If
    End Sub

    Sub Sort_Grid(ByVal sender As Object, _
        ByVal e As DataGridSortCommandEventArgs)

        ' Retrieve the data source from session state.
        Dim dt As DataTable = _
            CType(Session("Source"), DataTable)

        ' Create a DataView from the DataTable.
        Dim dv As DataView = New DataView(dt)

        ' The DataView provides an easy way to 
        ' sort. Simply set the Sort property with 
        ' the name of the field to sort by.
        dv.Sort = e.SortExpression

        ' Rebind the data source and specify that 
        ' it should be sorted by the field specified 
        ' in the SortExpression property.
        ItemsGrid.DataSource = dv
        ItemsGrid.DataBind()
    End Sub

    Sub Check_Change(ByVal sender As Object, _
        ByVal e As EventArgs)
        ' Allow or prevent sorting depending 
        ' on the user's selection.
        ItemsGrid.AllowSorting = _
            AllowSortingCheckBox.Checked

        ' After changing the property, rebind 
        ' the data to refresh the DataGrid control.

        ' Retrieve data source from session state.
        Dim dt As DataTable = _
            CType(Session("Source"), DataTable)

        ' Create a DataView from the DataTable.
        Dim dv As DataView = New DataView(dt)

        ' Rebind the data source.
        ItemsGrid.DataSource = dv
        ItemsGrid.DataBind()
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>
        ExtractTemplateRows Example
    </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <h3>DataGrid AllowSorting Example</h3>

      <p>Select whether to allow sorting in the DataGrid control.<br />
      <asp:CheckBox id="AllowSortingCheckBox"
           Text="Allow sorting"
           AutoPostBack="True"
           Checked="True"
           OnCheckedChanged="Check_Change"
           runat="server"/></p>
      <hr />

      <b>Product List</b>
      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           OnSortCommand="Sort_Grid"
           UseAccessibleHeader="true" 
           AutoGenerateColumns="False"
           AllowSorting="True"
           runat="server">

         <HeaderStyle BackColor="#00aaaa" />
         <Columns>
            <asp:BoundColumn DataField="IntegerValue" 
                 SortExpression="IntegerValue"
                 HeaderText="Item"/>

            <asp:BoundColumn DataField="StringValue"
                 SortExpression="StringValue" 
                 HeaderText="Description"/>

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

               <ItemStyle HorizontalAlign="Right">
               </ItemStyle>
            </asp:BoundColumn>
         </Columns> 
      </asp:DataGrid>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    ICollection CreateDataSource()
    {
        // Create a Random object to mix up the 
        // order of items in the sample data.
        Random randNum = new Random();

        // Create sample data for the DataGrid control.
        DataTable dt = new DataTable();

        // Define the columns of the table.
        dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
        dt.Columns.Add(new DataColumn("StringValue", typeof(String)));
        dt.Columns.Add(new DataColumn("CurrencyValue", typeof(Double)));

        // Populate the table with sample values.
        for (int i = 0; i <= 8; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = "Item " + randNum.Next(1, 15).ToString();
            dr[2] = 1.23 * randNum.Next(1, 15);
            dt.Rows.Add(dr);
        }

        // To persist the data source between posts to the server,
        // store it in session state.  
        Session["Source"] = dt;
        DataView dv = new DataView(dt);
        return dv;
    }

    void Page_Load(Object sender, EventArgs e)
    {
        // Load sample data only once, when the page is first loaded.
        if (!IsPostBack)
        {
            ItemsGrid.DataSource = CreateDataSource();
            ItemsGrid.DataBind();
        }
    }

    void Sort_Grid(Object sender, DataGridSortCommandEventArgs e)
    {
        // Retrieve the data source from session state.
        DataTable dt = (DataTable)Session["Source"];

        // Create a DataView from the DataTable.
        DataView dv = new DataView(dt);

        // The DataView provides an easy way to sort. Simply set the
        // Sort property with the name of the field to sort by.
        dv.Sort = e.SortExpression;

        // Rebind the data source and specify that it should be sorted
        // by the field specified in the SortExpression property.
        ItemsGrid.DataSource = dv;
        ItemsGrid.DataBind();
    }

    void Check_Change(Object sender, EventArgs e)
    {
        // Allow or prevent sorting depending on the user's selection.
        ItemsGrid.AllowSorting = AllowSortingCheckBox.Checked;

        // After changing the property, rebind the data to
        // refresh the DataGrid control.

        // Retrieve the data source from session state.
        DataTable dt = (DataTable)Session["Source"];

        // Create a DataView from the DataTable.
        DataView dv = new DataView(dt);

        // Rebind the data source.
        ItemsGrid.DataSource = dv;
        ItemsGrid.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>
        ExtractTemplateRows Example
    </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <h3>DataGrid AllowSorting Example</h3>

      <p>Select whether to allow sorting in the DataGrid control.<br />
      <asp:CheckBox id="AllowSortingCheckBox"
           Text="Allow sorting"
           AutoPostBack="True"
           Checked="True"
           OnCheckedChanged="Check_Change"
           runat="server"/></p>
      <hr />

      <b>Product List</b>
      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           OnSortCommand="Sort_Grid"
           UseAccessibleHeader="true"
           AutoGenerateColumns="False"
           AllowSorting="True"
           runat="server">

         <HeaderStyle BackColor="#00aaaa" />
         <Columns>
            <asp:BoundColumn DataField="IntegerValue" 
                 SortExpression="IntegerValue"
                 HeaderText="Item"/>

            <asp:BoundColumn DataField="StringValue"
                 SortExpression="StringValue" 
                 HeaderText="Description"/>

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

               <ItemStyle HorizontalAlign="Right">
               </ItemStyle>
            </asp:BoundColumn>
         </Columns> 
      </asp:DataGrid>

   </div>
   </form>
</body>
</html>

Consulte também

Referência

DataGrid

Outros recursos

controle de servidor Web sintaxe