本文匯總 GridView 23 種典型用法,涵蓋數據操作、UI 定制、客戶端交互、導出導入、嵌套、分頁排序等,為 WebForms 維護者提供速查手冊。
| # | 功能 | 關鍵技術點 |
|---|---|---|
| 1 | 無後台代碼增刪改查 | SqlDataSource + CommandField + 模板列 |
| 2 | 添加新記錄 | FooterTemplate + Insert 模板 + RowCommand |
| 3 | 編輯更新 | EditIndex + EditItemTemplate + RowUpdating |
| 4 | 批量更新 | 遍歷 Rows 收集值 + 事務批量 SQL |
| 5 | 固定表頭 | CSS position:sticky / JavaScript 克隆表頭 |
| 6 | 合並單元格 | RowDataBound 修改 RowSpan/ColSpan |
| 7 | Footer 顯示統計 | RowDataBound 累計 + FooterTemplate 綁定 |
| 8 | 添加表頭組 | RowCreated 動態添加 TableRow |
| 9 | 導出 Excel | Response.ContentType + RenderControl + HtmlForm |
| 10 | 導入 Excel | OleDb/NPOI/EPPlus 讀取 → 綁定 |
| 11 | 主從嵌套 | 子 GridView 在 TemplateField 中 + RowDataBound 綁定 |
| 12 | 多級嵌套 | 遞歸模板 / 展開折疊狀態管理 |
| 13 | 排序 | AllowSorting + SortExpression + Sorting 事件重綁 |
| 14 | 分頁 | AllowPaging + PageIndexChanging + 自定義 PagerTemplate |
| 15 | CheckBox 全選/反選 | Header CheckBox + JS 遍歷 / 服務端遍歷 Rows |
| 16 | DropDownList 篩選 | 模板列綁定 + SelectedIndexChanged 重綁 |
| 17 | RadioButton 單選 | 分組名一致 + 服務端查找選中行 |
| 18 | 內嵌 DropDownList 編輯 | EditItemTemplate 綁定數據源 + DataBind |
| 19 | 客戶端 JS 配合 CheckBox | ClientID 模式 + jQuery 選中值回傳 |
| 20 | 行背景色隔行/懸停 | RowDataBound 設置 CssClass / CSS :nth-child |
| 21 | 行雙擊/右鍵菜單 | Attributes 添加 ondblclick / contextmenu |
| 22 | 行屬性動態設置 | RowDataBound 設置 ToolTip/Style/Id |
| 23 | DataKeyNames 主鍵使用 | DataKeys[RowIndex].Value 獲取主鍵,避免隱藏列 |
EnableViewState="false" 大幅減小頁面體積,需每次請求重綁數據。ObjectDataSource / 手動綁定 List<T>,避免 SqlDataSource 耦合 SQL。ROW_NUMBER,避免全表查詢再內存分頁。Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=Export.xls"); Response.ContentType = "application/ms-excel"; GridView.RenderControl(htmlWriter); 需重寫 VerifyRenderingInServerForm。新項目請直接使用前端表格組件:
MudBlazor DataGrid、Radzen Grid,C# 全棧體驗。