GridView 顯示資料列表時,常需第一欄顯示流水號(序號)。三種常見需求:
<asp:TemplateField HeaderText="序號" InsertVisible="False">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
Container.DataItemIndex 為當前頁內索引(0-based)。
<asp:TemplateField HeaderText="序號" InsertVisible="False">
<ItemStyle HorizontalAlign="Center" />
<HeaderStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="lblSeq" runat="server"
Text='<%# this.GridView1.PageIndex * this.GridView1.PageSize + Container.DataItemIndex + 1 %>' />
</ItemTemplate>
</asp:TemplateField>
PageIndex * PageSize + DataItemIndex + 1this.GridView1 需在頁面類別中可存取(protected 或 public)。
<asp:BoundField HeaderText="序號" />
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int seq = GridView1.PageIndex * GridView1.PageSize + e.Row.RowIndex + 1;
e.Row.Cells[0].Text = seq.ToString();
}
}
e.Row.RowIndex 為當前頁內索引,等同 DataItemIndex。AutoGenerateColumns="False" 且 BoundField 為第一欄(Cells[0])。| 方式 | 分頁支援 | 程式碼位置 | 擴充性 | 適用場景 |
|---|---|---|---|---|
| Container.DataItemIndex | ❌ 重置 | .aspx | 低 | 簡單列表、無分頁、原型開發 |
| 前端運算式 | ✅ 累加 | .aspx | 中 | 標準報表、不想寫後端 |
| RowDataBound | ✅ 累加 | .aspx.cs | 高 | 複雜編號規則、條件格式、動態欄位 |
若 GridView 啟用 AllowSorting 或自訂篩選,流水號應反映**目前顯示順序**,上述三種方式均自然滿足(綁定後的 DataSource 順序即顯示順序)。若需「資料庫原始 ID」不變,請直接綁定資料表主鍵欄位而非流水號。