DataGrid.AllowCustomPaging Propriedade

Definição

Obtém ou define um valor que indica se a paginação personalizada está habilitada.Gets or sets a value that indicates whether custom paging is enabled.

public:
 virtual property bool AllowCustomPaging { bool get(); void set(bool value); };
public virtual bool AllowCustomPaging { get; set; }
member this.AllowCustomPaging : bool with get, set
Public Overridable Property AllowCustomPaging As Boolean

Valor da propriedade

true se a paginação personalizada estiver habilitada, caso contrário, false.true if custom paging is enabled; otherwise, false. O valor padrão é false.The default value is false.

Exemplos

O exemplo de código a seguir demonstra como usar a propriedade AllowCustomPaging para habilitar a paginação personalizada.The following code example demonstrates how to use the AllowCustomPaging property to enable custom paging.

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

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

Comentários

A paginação permite que você exiba o conteúdo do controle de DataGrid em segmentos de página.Paging allows you to display the contents of the DataGrid control in page segments. O número de itens em uma página é determinado pela propriedade PageSize.The number of items on a page is determined by the PageSize property. Se nenhum valor for especificado para a propriedade PageSize, o DataGrid exibirá 10 itens em uma página.If no value is specified for the PageSize property, the DataGrid will display 10 items on a page.

Normalmente, uma fonte de dados que contém cada linha no controle de DataGrid é carregada toda vez que o controle de DataGrid se move para uma página diferente.Normally, a data source that contains every row in the DataGrid control is loaded every time the DataGrid control moves to a different page. Isso pode consumir muitos recursos quando a fonte de dados é muito grande.This can consume a lot of resources when the data source is very large. A paginação personalizada permite carregar apenas o segmento de dados necessário para exibir uma única página.Custom paging allows you to load just the segment of data needed to display a single page.

Para habilitar a paginação personalizada, defina as propriedades AllowPaging e AllowCustomPaging como true.To enable custom paging, set both the AllowPaging and AllowCustomPaging properties to true. Em seguida, forneça o código para manipular o evento de PageIndexChanged.Next, provide code to handle the PageIndexChanged event.

A lógica típica para o manipulador de eventos PageIndexChanged é primeiro definir a propriedade CurrentPageIndex como o índice da página que você deseja exibir.The typical logic for the PageIndexChanged event handler is to first set the CurrentPageIndex property to the index of the page you want to display.

Observação

O manipulador de eventos recebe um objeto DataGridPageChangedEventArgs como um parâmetro.The event handler receives a DataGridPageChangedEventArgs object as a parameter. Você pode usar a propriedade NewPageIndex desse parâmetro para determinar o índice da página selecionada pelo usuário a partir dos elementos de seleção de página do controle de DataGrid.You can use the NewPageIndex property of this parameter to determine the index of the page selected by the user from the page selection elements of the DataGrid control.

Em seguida, crie uma fonte de dados que contenha os dados a serem exibidos em uma única página e use o método DataBind para associar os dados ao controle de DataGrid.Next, create a data source that contains the data to display on a single page and then use the DataBind method to bind the data to the DataGrid control.

Observação

Como apenas um segmento dos dados é carregado, você deve definir a propriedade VirtualItemCount como o número total de itens no controle de DataGrid.Because only a segment of the data is loaded, you must set the VirtualItemCount property to the total number of items in the DataGrid control. Isso permite que o controle determine o número total de páginas necessárias para exibir cada item no controle de DataGrid.This allows the control to determine the total number of pages needed to display every item in the DataGrid control. Essa propriedade normalmente é definida de forma programática quando o número total de itens no controle de DataGrid é determinado.This property is normally programmatically set once the total number of items in the DataGrid control is determined.

Quando a paginação está habilitada com a propriedade AllowCustomPaging é definida como false, o controle de DataGrid pressupõe que a fonte de dados contém todos os itens a serem exibidos.When paging is enabled with the AllowCustomPaging property is set to false, the DataGrid control assumes that the data source contains all the items to be displayed. O controle de DataGrid calcula os índices dos itens na página exibida com base no índice de página, especificado pela propriedade CurrentPageIndex e o número de itens em uma página, especificados pela propriedade PageSize.The DataGrid control calculates the indexes of the items on the displayed page based on the page index, specified by the CurrentPageIndex property, and the number of items on a page, specified by the PageSize property.

Quando a propriedade AllowCustomPaging é definida como true, o controle de DataGrid pressupõe que a fonte de dados contém apenas os itens, conforme determinado pela propriedade VirtualItemCount.When the AllowCustomPaging property is set to true, the DataGrid control assumes that the data source only contains the items as determined by the VirtualItemCount property. Todos os itens até o número de itens especificados pela propriedade PageSize são exibidos.All items up to the number of items specified by the PageSize property are displayed.

Aplica-se a

Veja também