1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#】Web FormでListViewを使って表示する方法(ページネーション付き)

1
Posted at

ASP.NET WebFormsアプリを使ってListViewオブジェクトを使ったサンプルを作ってみます。
ついでに、ページング処理も併せて作ります。

完成イメージ

初期表示時の画面
image.png

番号2をクリックしたときの画面
image.png

最後尾をクリックしたときの画面

image.png

フロント側のコード

sample3.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="sample3.aspx.cs" Inherits="WebApplicationWebForm.sample3" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form2" runat="server">
        <asp:ListView ID="ListViewClass" runat="server" 
            AllowPaging="true" AllowSorting="true"
            OnItemDataBound="ListViewClass_ItemDataBound"
            OnSorting="ListViewClass_Sorting"
            OnPagePropertiesChanging="ListViewClass_PagePropertiesChanging">
            <LayoutTemplate>
                <table border="1">
                    <thead>
                        <tr>
                            <th><asp:LinkButton ID="SortEmployeeId" runat="server" CommandName="Sort" CommandArgument="employeeId">従業員ID</asp:LinkButton></th>
                            <th><asp:LinkButton ID="SortDepartment" runat="server" CommandName="Sort" CommandArgument="department">所属部署</asp:LinkButton></th>
                            <th><asp:LinkButton ID="SortSection" runat="server" CommandName="Sort" CommandArgument="section">所属課</asp:LinkButton></th>
                            <th><asp:LinkButton ID="SortJobClass" runat="server" CommandName="Sort" CommandArgument="jobclass">役職</asp:LinkButton></th>
                            <th><asp:LinkButton ID="SortName" runat="server" CommandName="Sort" CommandArgument="name">従業員名</asp:LinkButton></th>
                            <th><asp:LinkButton ID="SortSex" runat="server" CommandName="Sort" CommandArgument="sex">性別</asp:LinkButton></th>
                            <th><asp:LinkButton ID="SortIP" runat="server" CommandName="Sort" CommandArgument="ipaddress">IPaddress</asp:LinkButton></th>
                            <th><asp:LinkButton ID="SortIPAlloc" runat="server" CommandName="Sort" CommandArgument="ipaddressalocation">IPaddressの割り振り</asp:LinkButton></th>
                        </tr>
                    </thead>
                    <tbody>
                        <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
                    </tbody>
                </table>
            </LayoutTemplate>
            <ItemTemplate>
                <tr>
                    <td><%# Eval("EmployeeId") %></td>
                    <td><%# Eval("Department") %></td>
                    <td><%# Eval("Section") %></td>
                    <td><%# Eval("JobClass") %></td>
                    <td><%# Eval("Name") %></td>
                    <td><%# Eval("Sex") %></td>
                    <td><%# Eval("Ipaddress") %></td>
                    <td><%# Convert.ToBoolean(Eval("IpaddressAlocation")) ? "○" : "×" %></td>
                </tr>
            </ItemTemplate>
        </asp:ListView>

        <!-- ✅ ページングボタン(外に1つだけ設置) -->
        <div style="margin-top:10px; text-align:center;">
            <asp:DataPager ID="DataPager1" runat="server" PagedControlID="ListViewClass" PageSize="2">
        <Fields>
            <asp:NextPreviousPagerField 
                ShowFirstPageButton="true" 
                ShowPreviousPageButton="false"
                ShowNextPageButton="false"
                ShowLastPageButton="false"
                FirstPageText="先頭" 
                ButtonType="Link" />

            <asp:NumericPagerField 
                ButtonCount="10" 
                ButtonType="Link" />

            <asp:NextPreviousPagerField 
                ShowFirstPageButton="false"
                ShowPreviousPageButton="false"
                ShowNextPageButton="false"
                ShowLastPageButton="true"
                LastPageText="最後尾"
                ButtonType="Link" />
        </Fields>
            </asp:DataPager>
        </div>
    </form>
</body>
</html>

サーバサイドのコード

全件データ取得 → ページングは DataPager に任せる

ASP.NET WebForms ListView + DataPager の正しい構成では:

全件データを ListView.DataSource に渡し、DataPager にページ分けをさせる

という仕組みにする必要があります。

sample3.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using WebApplicationWebForm.Models;

namespace WebApplicationWebForm
{
    public partial class sample3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) 
            {
                LoadListView();// 初期ページ読み込み LoadListView(0,20);
            }
        }

        
        protected void ListViewClass_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "Sort")
            {
                string sortField = e.CommandArgument.ToString();
                if (SortExpression == sortField)
                {
                    SortDirection = (SortDirection == "ASC") ? "DESC" : "ASC";
                }
                else
                {
                    SortExpression = sortField;
                    SortDirection = "ASC";
                }

                LoadListView();  // ← ページサイズ2に統一 LoadListView(GetPageIndex(), 2);
            }
        }

        protected void ListViewClass_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                var employee = (Employee)((ListViewDataItem)e.Item).DataItem;

                // 性別によって色を変更
                if (employee.Sex == "男")
                {
                    //e.Item.BackColor = System.Drawing.Color.LightBlue;
                }
                else if (employee.Sex == "女")
                {
                    //e.Item.BackColor = System.Drawing.Color.MistyRose;
                }
            }
        }


        private void LoadListView()//
        {
            string connStr = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;
            List<Employee> employeeList = new List<Employee>();

            using (SqlConnection conn = new SqlConnection(connStr))
            {
                /*
                string sql = $@"
                    SELECT employeeId, department, section, jobclass, name, sex, ipaddress, ipaddressalocation 
                    FROM [test].[dbo].[employee]
                    ORDER BY {SortExpression} {SortDirection}
                    OFFSET @Offset ROWS FETCH NEXT @PageSize ROWS ONLY";
                */
                string sql = $@"
                    SELECT employeeId, department, section, jobclass, name, sex, ipaddress, ipaddressalocation 
                    FROM [test].[dbo].[employee]
                    ORDER BY {SortExpression} {SortDirection}";  // ← OFFSET なし!

                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    //int offset = pageIndex * pageSize;
                    //cmd.Parameters.AddWithValue("@Offset", offset);
                    //cmd.Parameters.AddWithValue("@PageSize", pageSize);
                    conn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        employeeList.Add(new Employee
                        {
                            EmployeeId = Convert.ToInt32(reader["employeeId"]),
                            Department = reader["department"].ToString(),
                            Section = reader["section"].ToString(),
                            JobClass = reader["jobclass"].ToString(),
                            Name = reader["name"].ToString(),
                            Sex = reader["sex"].ToString(),
                            Ipaddress = reader["ipaddress"].ToString(),
                            IpaddressAlocation = reader["ipaddressalocation"] != DBNull.Value ? Convert.ToBoolean(reader["ipaddressalocation"]) : false
                        });
                    }
                }
            }

            ListViewClass.DataSource = employeeList;
            ListViewClass.DataBind();
        }
        
        private int GetPageIndex()
        {
            return (DataPager1.StartRowIndex / DataPager1.PageSize);
        }
        

        private string SortExpression
        {
            get => ViewState["SortExpression"] as string ?? "employeeId";
            set => ViewState["SortExpression"] = value;
        }

        private string SortDirection
        {
            get => ViewState["SortDirection"] as string ?? "ASC";
            set => ViewState["SortDirection"] = value;
        }

        protected void ListViewClass_Sorting(object sender, ListViewSortEventArgs e)
        {
            if (SortExpression == e.SortExpression)
            {
                SortDirection = (SortDirection == "ASC") ? "DESC" : "ASC";
            }
            else
            {
                SortExpression = e.SortExpression;
                SortDirection = "ASC";
            }

            LoadListView();  // ← ページサイズ2に統一 LoadListView(GetPageIndex(), 2);
        }

        protected void ListViewClass_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
        {
            DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
            int pageIndex = e.StartRowIndex / e.MaximumRows;
            LoadListView();//pageIndex, e.MaximumRows
        }



    }

    public class Employee
    {
        public int EmployeeId { get; set; }
        public string Department { get; set; }
        public string Section { get; set; }
        public string JobClass { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }
        public string Ipaddress { get; set; }
        public bool IpaddressAlocation { get; set; }
    }


}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?