Share via


DataGrid 웹 서버 컨트롤 선언 구문

업데이트: 2007년 11월

DataGrid 컨트롤은 데이터 바인딩된 표를 렌더링합니다. 이 컨트롤을 사용하면 다양한 형식의 열을 정의하여 모눈에서 바인딩된 열 또는 템플릿 열과 같은 셀 내용의 레이아웃을 제어할 수 있고 단추 열이나 하이퍼링크 열 편집 등과 같은 특정 기능을 추가할 수 있습니다. 이 컨트롤에서는 페이지 단위로 데이터를 탐색하기 위한 다양한 옵션도 지원합니다.

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

설명

DataGrid 컨트롤을 사용하기 전에 GridView 컨트롤을 대신 사용해 보십시오. GridView 컨트롤은 .NET Framework 버전 2.0에 새로 추가되었으며 이전 버전의 DataGrid 컨트롤 대신 사용됩니다.

DataGrid 컨트롤을 사용하면 데이터 소스의 필드를 표에 열로 표시할 수 있습니다. DataGrid 컨트롤의 각 행은 데이터 소스의 레코드를 나타냅니다. DataGrid 컨트롤은 선택, 편집, 삭제, 페이징 및 정렬 기능을 지원합니다.

기본적으로 AutoGenerateColumns 속성은 true로 설정되므로 데이터 소스의 각 필드에 대해 BoundColumn 개체가 생성됩니다. 그런 다음 각 필드는 데이터 소스에 나타나는 순서대로 DataGrid 컨트롤에 열로 렌더링됩니다.

DataGrid 컨트롤에 표시할 열을 직접 지정하려면AutoGenerateColumns 속성을 false로 설정한 다음, 포함할 열의 목록을 열기 및 닫기 <Columns> 태그 사이에 나열하면 됩니다. 지정된 열은 나열된 순서에 따라 Columns 컬렉션에 추가됩니다. 이렇게 하면 DataGrid 컨트롤의 열을 프로그래밍 방식으로 제어할 수 있습니다.

참고

DataGrid 컨트롤에 열이 표시되는 순서는 Columns 컬렉션에서 해당 열이 나타나는 순서에 따라 결정됩니다. Columns 컬렉션을 조작하여 프로그래밍 방식으로 열의 순서를 변경할 수는 있지만 표시 순서대로 열을 나열하는 것이 더 간편합니다.

참고

자동으로 생성된 열과 함께 명시적으로 선언한 열을 사용할 수 있습니다. 두 가지 열을 모두 사용할 경우에는 명시적으로 선언한 열이 먼저 렌더링된 다음 자동으로 생성된 열이 렌더링됩니다. 자동으로 생성된 열은 Columns 컬렉션에 추가되지 않습니다.

서로 다른 열 형식에 따라 컨트롤에서 열의 동작이 결정됩니다. DataGrid 컨트롤에서는 다음과 같은 열 형식을 사용할 수 있습니다.

열 형식

설명

EditCommandColumn

가장 일반적인 편집 명령(Edit, Update, Cancel)을 미리 정의된 열 형식에 캡슐화합니다.

HyperLinkColumn

데이터 필드의 값에 바인딩되는 하이퍼링크 집합을 가진 열을 만듭니다. 예를 들어 주문 목록을 표시하는 표에 하이퍼링크 열을 포함할 수 있습니다. 이 열에서 OrderID 필드는 주문 세부 내용을 표시하는 페이지에 대한 하이퍼링크로 렌더링됩니다.

BoundColumn

데이터 소스의 필드에 바인딩되고 스타일을 사용하여 표 셀에서 렌더링되는 열을 만듭니다. DataGrid 컨트롤의 기본 열 형식입니다.

ButtonColumn

열의 각 항목에 대해 Add 또는 Remove와 같은 사용자 정의 명령 단추를 포함하는 열을 만듭니다.

TemplateColumn

이 형식을 사용하여 열을 만들면 사용자 지정 HTML 요소와 컨트롤을 위한 템플릿을 사용하여 컨트롤의 레이아웃을 정의할 수 있습니다.

다음 표에서는 DataGrid 컨트롤에 선언할 수 있는 열에 대해 설명합니다.

DataGridColumn 기본 속성

다음 속성은 모든 DataGrid 열 형식에서 사용할 수 있습니다.

속성

설명

FooterText

열의 아래쪽 가장자리에 표시할 텍스트

HeaderImageUrl

열 머리글에서 HeaderText 텍스트 대신 렌더링되는 이미지의 URL

HeaderText

열의 위쪽 가장자리에 표시할 텍스트

Owner

바인딩된 열의 소유자인 DataGrid 컨트롤에 대한 참조(읽기 전용)

이 속성은 프로그래밍 단계에서만 사용합니다.

SortExpression

사용자가 열의 내용을 기준으로 정렬하도록 지정할 경우, 데이터 소스를 정렬하기 위한 필드의 이름

Visible

열이 표시되면 true이고, 그렇지 않으면 false입니다.

BoundColumn 속성

속성

설명

DataField

DataSource 데이터 소스에서 열에 대한 개체의 필드 또는 속성

DataFormatString

셀에 필드를 표시하는 방법을 지정하는 서식 지정 식 문자열. Format 메서드에서 사용하는 서식 지정 식과 비슷합니다.

ReadOnly

행이 편집 모드에 있을 때 열을 편집할 수 없으면 true이고, 그렇지 않으면 false입니다.

ButtonColumn 속성

속성

설명

ButtonType

렌더링할 단추의 종류. 기본값은 LinkButton입니다.

프로그래밍하는 경우 ButtonColumnType을 사용하여 이 속성을 설정합니다.

CommandName

열에서 단추를 클릭했을 때 전송되는 명령을 가리키는 문자열. 이 문자열은 e이벤트 인수 개체의 CommandSource 속성을 통해 이벤트 처리 메서드에서 사용할 수 있습니다.

DataGrid 컨트롤은 특정 표준 명령 이름을 인식합니다. 이러한 명령 이름에는 Select, Sort, Update, Cancel, Edit, Delete, Page 등이 포함됩니다.

DataTextField

ButtonColumn에 있는 단추의 Text 속성에 바인딩되는 DataSource의 필드 이름

DataTextFormatString

셀에 필드를 표시하는 방법을 지정하는 서식 지정 식 문자열

Text

이 열의 단추에 표시되는 캡션. DataTextField를 설정하면 이 값이 재정의됩니다.

TemplateColumn 속성

속성

설명

EditItemTemplate

편집 모드에 있을 때 열을 정의하는 HTML 요소와 컨트롤

FooterTemplate

열의 바닥글을 정의하는 HTML 요소와 컨트롤

HeaderTemplate

열의 머리글을 정의하는 HTML 요소와 컨트롤

ItemTemplate

열을 표시할 때 그 열을 정의하는 HTML 요소와 컨트롤

HyperLinkColumn 속성

속성

설명

DatahrefField

DataSource에서 이동할 대상 페이지의 URL을 제공하는 개체의 속성 또는 필드

DatahrefFormatString

Text 속성에 사용할 서식 지정 식

DataTextField

DataSource 데이터 소스에서 열의 Text 속성에 대한 개체의 필드 또는 속성

DataTextFormatString

컨트롤에서 Text 속성이 표시되는 방법을 지정하는 서식 지정 문자열

href

이동할 페이지의 URL. DatahrefField를 설정하면 이 속성이 재정의됩니다.

Target

페이지를 표시하는 대상 창. _TOP과 같이 창 또는 프레임 참조의 이름이 될 수 있습니다.

Text

하이퍼링크의 텍스트

EditCommandColumn 속성

속성

설명

ButtonType

렌더링할 단추의 종류. 기본값은 LinkButton입니다.

프로그래밍하는 경우 ButtonColumnType을 사용하여 이 속성을 설정합니다.

EditText

Edit 단추에 표시되는 문자열

UpdateText

Update 단추에 표시되는 문자열

CancelText

Cancel 단추에 표시되는 문자열

DataGrid컨트롤의 다양한 부분에 스타일 속성을 설정하여 컨트롤의 모양을 사용자 지정할 수 있습니다. 다음 표에서는 DataGrid 컨트롤의 다양한 부분에 대한 스타일 속성을 보여 줍니다.

스타일 속성

스타일 속성

설명

스타일 클래스

AlternatingItemStyle

항목을 한 번씩 건너서 교대하는 스타일

TableItemStyle

EditItemStyle

편집 중인 항목의 스타일

TableItemStyle

FooterStyle

목록 끝에 바닥글이 있을 경우, 바닥글의 스타일

TableItemStyle

HeaderStyle

목록 시작 부분에 머리글이 있을 경우, 머리글의 스타일

TableItemStyle

ItemStyle

개별 항목의 스타일

Style

PagerStyle

페이지 선택 컨트롤의 스타일

DataGridPagerStyle

SelectedItemStyle

현재 선택된 항목의 스타일

TableItemStyle

각 스타일 클래스에 지원되는 속성에 대한 자세한 내용은 Style 개체 속성을 참조하십시오.

DataGrid 컨트롤에는 내용을 페이지 단위로 표시하는 기본 제공 기능이 포함되어 있습니다. 페이지에 표시할 항목의 수는 PageSize 속성을 통해 결정됩니다. PageSize 속성에 값을 지정하지 않으면 DataGrid 컨트롤은 한 번에 10개의 항목을 페이지에 표시합니다.

페이징 기능은 기본적으로 사용하지 않도록 설정되어 있습니다. 페이징 기능을 사용하려면 AllowPaging 속성을 true로 설정하고 PageIndexChanged 이벤트를 처리하는 코드를 제공합니다. 일반적으로 표시할 페이지의 인덱스를 CurrentPageIndex 속성에 설정한 다음 데이터 소스를 컨트롤에 다시 바인딩하는 논리를 사용하여 PageIndexChanged 이벤트를 처리합니다. 표시할 페이지의 인덱스는 이벤트 처리기에 전달된 DataGridPageChangedEventArgs 개체의 NewPageIndex 속성을 사용하여 액세스되는 경우가 많습니다.

표준 페이징 기능을 사용하는 경우 DataGrid 컨트롤에서는 표시할 모든 항목이 데이터 소스에 포함되어 있다고 가정합니다. DataGrid 컨트롤은 CurrentPageIndex 속성에 지정된 페이지 인덱스 및 PageSize 속성에 지정된 페이지 항목 수를 기준으로 현재 페이지에 있는 항목의 인덱스를 계산합니다.

DataGrid 컨트롤에서 생성한 <td> 및 <tr> 태그에 프로그래밍 방식으로 특성을 추가하여 DataGrid 컨트롤의 모양을 세부적으로 사용자 지정할 수 있습니다. ItemCreated 또는 ItemDataBound 이벤트에 대한 사용자 지정 이벤트 처리기를 제공하여 태그에 특성을 삽입할 수 있습니다. 일반적으로 ItemCreated 이벤트에 대한 이벤트 처리기에 특성을 추가합니다. 그러나 특성이 실제 데이터에 의존하는 경우에는 ItemDataBound 이벤트에 대한 처리기에 특성을 추가합니다.

<td> 태그에 특성을 추가하려면 먼저 DataGrid 컨트롤에서 특성을 추가할 셀을 나타내는 TableCell 개체를 가져옵니다. 이벤트 처리기에 전달된 DataGridItemEventArgs의 Item 속성(DataGridItemEventArgs 인덱서)에 대한 Control.Controls 컬렉션을 사용하여 원하는 TableCell을 가져올 수 있습니다. 그런 다음 TableCell에 대한 Attributes 컬렉션의 AttributeCollection.Add 메서드를 사용하여 <td> 태그에 특성을 추가할 수 있습니다.

<tr> 태그에 특성을 추가하려면 먼저 DataGrid 컨트롤에서 특성을 추가할 행을 나타내는 DataGridItem을 가져옵니다. 이벤트 처리기에 전달된 DataGridItemEventArgs의 Item 속성(DataGridItemEventArgs 인덱서)을 사용하여 원하는 DataGridItem을 가져올 수 있습니다. 그런 다음 DataGridItem에 대한 Attributes 컬렉션의 AttributeCollection.Add 메서드를 사용하여 <tr> 태그에 특성을 추가할 수 있습니다.

경고

텍스트는 DataGrid 컨트롤에 표시된 후에 HTML로 인코딩됩니다. 따라서 텍스트의 HTML 태그 내에 스크립트를 포함시킬 수 있습니다. 컨트롤 값을 사용자 입력에서 가져온 경우 값이 유효한지 확인하여 보안상의 허점을 방지합니다.

DataGrid 웹 서버 컨트롤의 속성과 이벤트에 대한 자세한 내용은 DataGrid 클래스 설명서를 참조하십시오.

예제

다음 예제에서는 DataGrid 컨트롤을 사용하여 데이터 소스의 항목을 표시하는 방법을 보여 줍니다.

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

다음 예제에서는 DataGrid 컨트롤에서 페이징 기능을 사용하는 방법을 보여 줍니다.

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

대개 DataGrid 컨트롤에서 한 페이지 분량의 정보를 표시할 때마다 목록의 모든 항목이 포함된 데이터 소스 전체가 로드됩니다. 이 때문에 데이터 소스가 매우 큰 경우에는 리소스가 많이 사용될 수 있습니다. 이 문제를 해결하기 위해 페이지를 표시하는 데 필요한 데이터 세그먼트만을 로드하도록 페이징 기능을 사용자 지정할 수도 있습니다.

사용자 지정 페이징 기능을 사용하려면 AllowPaging 속성과 AllowCustomPaging 속성을 true로 설정하고 PageIndexChanged 이벤트를 처리하는 코드를 제공합니다. 일반적으로 표시할 페이지의 인덱스를 CurrentPageIndex 속성에 설정한 다음 데이터 소스를 컨트롤에 다시 바인딩하는 논리를 사용하여 PageIndexChanged 이벤트를 처리합니다. 표시할 페이지의 인덱스는 이벤트 처리기에 전달된 DataGridPageChangedEventArgs 개체의 NewPageIndex 속성을 사용하여 액세스되는 경우가 많습니다. 그런 다음 한 페이지에 표시할 만큼의 데이터가 들어 있는 데이터 소스를 만듭니다. 데이터 소스를 만든 다음에는 DataBind 메서드를 사용하여 데이터 소스를 DataGrid 컨트롤에 바인딩합니다. 데이터의 일부만 로드되므로 DataGrid 컨트롤에 표시할 총 항목 수를 VirtualItemCount 속성에 설정합니다. 그러면 컨트롤에서는 컨트롤을 페이징하는 데 필요한 총 페이지 수를 계산할 수 있습니다.

사용자 지정 페이징을 사용하는 경우 DataGrid 컨트롤에서는 현재 페이지에 표시할 항목만 데이터 소스에 포함되어 있다고 가정합니다. PageSize 속성에 지정된 수만큼 데이터 소스의 모든 항목이 표시됩니다.

다음 코드 예제에서는 AllowCustomPaging 속성을 사용하여 사용자 지정 페이징 기능을 설정하는 방법을 보여 줍니다.

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

DataGrid 컨트롤에서는 정렬 기능도 기본으로 제공합니다. 정렬 기능을 사용하도록 설정되어 있는 경우에는 선택한 열을 기준으로 DataGrid를 정렬할 수 있는 LinkButton 컨트롤이 각 열의 머리글에 렌더링됩니다. LinkButton을 클릭하면 SortCommand 이벤트가 발생됩니다. 필요하면 이 이벤트에 대한 이벤트 처리기 코드를 작성할 수도 있습니다. 처리기에 대한 일반적인 논리는 목록을 정렬한 다음 데이터를 DataGrid에 다시 바인딩하는 것입니다.

다음 예제에서는 DataGrid 컨트롤에서 정렬 기능을 사용하는 방법을 보여 줍니다.

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

참고 항목

참조

DataGrid

기타 리소스

웹 서버 컨트롤 구문