ASP.NET

ASP.NET GridView でページング(実行可能サンプルDL)

2012年12月3日

ASP.NET の GridView でページングを使う実装例です。ページング時に発生する PageIndexChanging をハンドルしてページインデックス指定とデータの再バインドをします。

ASPX

まずは UI 部分の実装です。GridView コントロールを宣言し、AllowPaging プロパティに True を設定します。また、ページインデックスが切り替わった際に発生する、PageIndexChanging イベントを購読します。

<asp:GridView
    ID="GridView1"
    runat="server"
    Height="402px"
    Width="655px"
    AllowPaging="True"
    OnPageIndexChanging="GridView1_PageIndexChanging"
    >
</asp:GridView>

C#

続いて、ロジック部分の実装に移ります。Page_Load イベントの中で、ダミーデータを生成しています。また、ページ切り替え時に、対応するページのデータをバインドするように GridView に指示します。

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Session["data"] に DataTable オブジェクトが格納されていない場合、if ブロック内を実行する。
        if (Session["data"] == null)
        {
            #region DataTable オブジェクトを作成する。
            DataColumn[] PrimaryColumn = new DataColumn[1];
            DataTable datatable = new DataTable();
            PrimaryColumn[0] = datatable.Columns.Add("ID", typeof(string));
            datatable.Columns.Add("ProductName", typeof(string));
            datatable.Columns.Add("Description", typeof(string));
            for (int i = 0; i < 100; i++)
            {
                datatable.Rows.Add(i.ToString(), "Product : " + i.ToString(), "Note : " + i.ToString());
            }
            datatable.PrimaryKey = PrimaryColumn;
            #endregion

            // Session["data"] に、DataTable オブジェクトを格納する。
            Session["data"] = datatable;
        }

        // Session["data"] から取り出した DataTable を、GridView にバインドする。
        this.GridView1.DataSource = Session["data"];
        this.GridView1.DataBind();
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        // GridView に対して、切り替え先のページインデックスを明示する。
        this.GridView1.PageIndex = e.NewPageIndex;
        
        // GridView にデータをバインドし直す。
        this.GridView1.DataBind();
    }
}

実行結果

次のように、ページ切り替えに応じて、ページに対応するデータが表示されることが分かります。

サンプルダウンロード

今回紹介したアプリケーションサンプルは、こちらからダウンロードできます。

参考情報

paging in gridview in asp.net
http://www.codeproject.com/Questions/262776/paging-in-gridview-in-asp-net

おすすめの学習リソース

ASP.NET Web Forms を網羅的に学習する場合、独習ASP.NET Webフォーム 第6版 がおすすめです。懇切丁寧に様々な技術要素が解説されています。もちろん、GridView に関する解説もなされています。一冊あると開発プロジェクトで重宝します。

-ASP.NET