gridview-sorting-indicator ソースコード全文
ASPNET_GridView_Sort_CS.sln
Microsoft Visual Studio Solution File, Format Version 12.00# Visual Studio Version 17VisualStudioVersion = 17.10.35004.147MinimumVisualStudioVersion = 10.0.40219.1Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "ASPNET_GridView_Sort_CS", "ASPNET_GridView_Sort_CS\", "{B0181C29-A33C-4D09-9090-5108DA2D5077}" ProjectSection(WebsiteProperties) = preProject TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.8" Debug.AspNetCompiler.VirtualPath = "/localhost_63559" Debug.AspNetCompiler.PhysicalPath = "ASPNET_GridView_Sort_CS\" Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_63559\" Debug.AspNetCompiler.Updateable = "true" Debug.AspNetCompiler.ForceOverwrite = "true" Debug.AspNetCompiler.FixedNames = "false" Debug.AspNetCompiler.Debug = "True" Release.AspNetCompiler.VirtualPath = "/localhost_63559" Release.AspNetCompiler.PhysicalPath = "ASPNET_GridView_Sort_CS\" Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_63559\" Release.AspNetCompiler.Updateable = "true" Release.AspNetCompiler.ForceOverwrite = "true" Release.AspNetCompiler.FixedNames = "false" Release.AspNetCompiler.Debug = "False" VWDPort = "63559" SlnRelativePath = "ASPNET_GridView_Sort_CS\" DefaultWebSiteLanguage = "Visual C#" EndProjectSectionEndProjectGlobal GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {B0181C29-A33C-4D09-9090-5108DA2D5077}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B0181C29-A33C-4D09-9090-5108DA2D5077}.Debug|Any CPU.Build.0 = Debug|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {A4D1C5AB-2E85-422E-BA68-17E3E12BCBE8} EndGlobalSectionEndGlobalASPNET_GridView_Sort_CS/Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowSorting="true" OnSorting="GridView1_Sorting" OnRowDataBound="GridView1_RowDataBound" > <Columns> <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" /> <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> <asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" /> </Columns> </asp:GridView> </div> </form></body></html>ASPNET_GridView_Sort_CS/Default.aspx.cs
using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindGrid(); } }
private void BindGrid(string sortExpression = null, string sortDirection = null) { var dataSource = GetData();
if (sortExpression != null) { DataView dv = dataSource.DefaultView; dv.Sort = sortExpression + " " + sortDirection; GridView1.DataSource = dv; } else { GridView1.DataSource = dataSource; }
GridView1.DataBind(); }
private DataTable GetData() { DataColumn[] primaryColumn = new DataColumn[1]; DataTable dataTable = new DataTable(); primaryColumn[0] = dataTable.Columns.Add("ID", typeof(int)); dataTable.Columns.Add("Name", typeof(string)); dataTable.Columns.Add("Age", typeof(int)); dataTable.Rows.Add(1, "Junya", 23); dataTable.Rows.Add(2, "Kyoko", 25); dataTable.Rows.Add(3, "Emi", 24); dataTable.Rows.Add(4, "Tatsuya", 28); dataTable.Rows.Add(5, "Naoki", 33); dataTable.Rows.Add(6, "Yuka", 25); dataTable.Rows.Add(7, "Mami", 24); dataTable.PrimaryKey = primaryColumn; return dataTable; }
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { string sortExpression = e.SortExpression; string sortDirection = GetSortDirection(sortExpression);
BindGrid(sortExpression, sortDirection); }
private string GetSortDirection(string column) { // ViewState から前回のソートの状態を取得 string sortDirection = "ASC"; // デフォルトは昇順
string previousSortExpression = ViewState["SortExpression"] as string; string previousSortDirection = ViewState["SortDirection"] as string;
if (previousSortExpression != null && previousSortExpression == column) { // 前回と同じ列でソートする場合は、ソート順を逆にする sortDirection = previousSortDirection == "ASC" ? "DESC" : "ASC"; }
// 現在のソート状態を ViewState に保存 ViewState["SortExpression"] = column; ViewState["SortDirection"] = sortDirection;
return sortDirection; }
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { // ヘッダーでなければ処理をキャンセル if (e.Row.RowType != DataControlRowType.Header) { return; }
string sortExpression = ViewState["SortExpression"] as string; string sortDirection = ViewState["SortDirection"] as string;
// ソート情報が空であれば処理をキャンセル if (string.IsNullOrEmpty(sortExpression)) { return; }
// ソート対象の列を探してインディケーターを追加 foreach (TableCell cell in e.Row.Cells) { if (!cell.HasControls()) { return; }
LinkButton sortLinkButton = cell.Controls[0] as LinkButton; if (sortLinkButton != null && sortLinkButton.CommandArgument == sortExpression) { string sortIndicator = sortDirection == "ASC" ? " ▲" : " ▼"; sortLinkButton.Text = sortLinkButton.Text + sortIndicator; } } }}ASPNET_GridView_Sort_CS/packages.config
<?xml version="1.0" encoding="utf-8"?><packages> <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.1" targetFramework="net48" /></packages>ASPNET_GridView_Sort_CS/Web.config
<?xml version="1.0" encoding="utf-8"?><!-- ASP.NET アプリケーションの構成方法の詳細については、 https://go.microsoft.com/fwlink/?LinkId=169433 を参照してください --><configuration> <system.web> <compilation debug="true" targetFramework="4.8" /> <httpRuntime targetFramework="4.8" /> </system.web> <system.codedom> <compilers> <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" /> </compilers> </system.codedom></configuration>ASPNET_GridView_Sort_CS/Web.Debug.config
<?xml version="1.0" encoding="utf-8"?>
<!-- web.config 変換の使用方法の詳細については、https://go.microsoft.com/fwlink/?LinkId=125889 を参照してください -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <!-- 次の例では、"MyDB" という値を持つ "name" 属性が "Match" ロケーターで 見つかった場合にのみ、"SetAttributes" 変換によって "connectionString" の 値が "ReleaseSQLServer" を使用するように変更されます。
<connectionStrings> <add name="MyDB" connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/> </connectionStrings> --> <system.web> <compilation xdt:Transform="RemoveAttributes(debug)" /> <!--
次の例では、web.config ファイルの <customErrors> セクション全体が "Replace" 変換によって置き換えられます。 <system.web> ノードには customErrors セクションが 1 つしかないため、 "xdt:Locator" 属性を使用する必要はありません。
<customErrors defaultRedirect="GenericError.htm" mode="RemoteOnly" xdt:Transform="Replace"> <error statusCode="500" redirect="InternalError.htm"/> </customErrors> > --> </system.web></configuration>