萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET GridView 自動排序完整實作:動態切換排序欄位與方向、ViewState 持久化

功能需求

  • 點擊欄位標題進行排序 (升冪/降冪切換)。
  • 排序狀態 (欄位、方向) 跨 PostBack 保持。
  • 支援多欄位排序切換。
  • 資料來源為 `DataTable`,利用 `DefaultView.Sort` 客戶端排序 (資料量小時) 或資料庫 `ORDER BY` (大量資料)。

前端標記 Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
    <title>GridView 自動排序示範</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                AllowSorting="True" OnSorting="GridView1_Sorting"
                CellPadding="4" ForeColor="#333333" GridLines="None">
                <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>
                <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <RowStyle BackColor="#EFF3FB" />
                <AlternatingRowStyle BackColor="White" />
                <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            </asp:GridView>
        </div>
    </form>
</body>
</html>

關鍵屬性:

  • `AllowSorting="True"`:啟用排序功能,標題變為 LinkButton。
  • `OnSorting="GridView1_Sorting"`:排序事件處理器。
  • `SortExpression="欄位名"`:每個可排序欄位**必須**設定,傳遞給 `GridViewSortEventArgs`。

後端程式碼 Default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    // 排序狀態鍵值
    private const string SortExprKey = "SortExpression";
    private const string SortDirKey = "SortDirection";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // 初始化排序狀態 (儲存在 GridView Attributes 或 ViewState)
            GridView1.Attributes[SortExprKey] = "id";
            GridView1.Attributes[SortDirKey] = "ASC";
            BindGridView();
        }
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        string newSortExpr = e.SortExpression;
        string newSortDir = "ASC";

        // 判斷是否同欄位點擊 → 切換方向
        string currentSortExpr = GridView1.Attributes[SortExprKey];
        string currentSortDir = GridView1.Attributes[SortDirKey];

        if (newSortExpr == currentSortExpr)
        {
            newSortDir = (currentSortDir == "ASC") ? "DESC" : "ASC";
        }

        // 更新狀態
        GridView1.Attributes[SortExprKey] = newSortExpr;
        GridView1.Attributes[SortDirKey] = newSortDir;

        // 重新繫結
        BindGridView();
    }

    private void BindGridView()
    {
        string sortExpr = GridView1.Attributes[SortExprKey];
        string sortDir = GridView1.Attributes[SortDirKey];

        DataTable dt = GetData(); // 取得資料

        // 套用排序 (DataView 排序)
        if (!string.IsNullOrEmpty(sortExpr) && !string.IsNullOrEmpty(sortDir))
        {
            dt.DefaultView.Sort = $"{sortExpr} {sortDir}";
        }

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    private DataTable GetData()
    {
        var dt = new DataTable();
        dt.Columns.Add("id", typeof(string));
        dt.Columns.Add("name", typeof(string));
        dt.Columns.Add("age", typeof(int));

        dt.Rows.Add("000001", "hekui", 26);
        dt.Rows.Add("000002", "zhangyu", 26);
        dt.Rows.Add("000003", "zhukundian", 27);
        dt.Rows.Add("000004", "liyang", 25);
        dt.Rows.Add("000005", "caili", 27);
        return dt;
    }
}

進階:排序狀態儲存在 ViewState (比 Attributes 更標準)

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

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

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

private void BindGridView()
{
    DataTable dt = GetData();
    dt.DefaultView.Sort = $"{SortExpression} {SortDirection}";
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

大量資料優化:資料庫層排序

當資料超過數千筆,客戶端 `DataView.Sort` 效能不佳,應在 SQL 查詢中直接 `ORDER BY`:

private DataTable GetData(string sortExpr, string sortDir)
{
    string sql = $"SELECT id, name, age FROM Users ORDER BY {SanitizeSortExpr(sortExpr)} {SanitizeSortDir(sortDir)}";
    // 使用參數化查詢執行...
    // 注意:ORDER BY 不能參數化,必須嚴格白名單驗證 sortExpr, sortDir 防注入
    return ExecuteDataTable(sql);
}

private string SanitizeSortExpr(string expr) 
    => new[] { "id", "name", "age" }.Contains(expr) ? expr : "id";

private string SanitizeSortDir(string dir) 
    => dir == "DESC" ? "DESC" : "ASC";

UI 增強:標題顯示排序箭頭

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        foreach (DataControlFieldCell cell in e.Row.Cells)
        {
            if (cell.ContainingField is BoundField field && !string.IsNullOrEmpty(field.SortExpression))
            {
                LinkButton lnk = cell.Controls[0] as LinkButton; // 標題為 LinkButton
                if (lnk != null && field.SortExpression == SortExpression)
                {
                    lnk.Text += (SortDirection == "ASC") ? " ▲" : " ▼";
                }
            }
        }
    }
}

總結

GridView 內建排序功能只需設定 `AllowSorting`、`SortExpression` 與 `OnSorting` 事件,核心邏輯在於**儲存與切換排序運算式 (欄位 + 方向)**,並在 `BindGridView` 中套用至 `DataView.Sort` 或 SQL `ORDER BY`。使用 `ViewState` 持久化排序狀態比 `Attributes` 更符合 Web Forms 狀態管理模式。搭配 `RowDataBound` 動態加入排序箭頭,可提供完整使用者體驗。

copyright © 萬盛學電腦網 all rights reserved