在 GridView 中放置 CheckBox,勾選時高亮該行,取消勾選恢復原色,提升用戶視覺反饋。
<asp:GridView ID="gvStudent" runat="server" AutoGenerateColumns="False" DataKeyNames="Id">
<Columns>
<asp:TemplateField HeaderText="選擇">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:CheckBox ID="ckbSelect" runat="server" AutoPostBack="true" OnCheckedChanged="ckbSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="姓名" />
<asp:BoundField DataField="Age" HeaderText="年齡" />
<asp:BoundField DataField="Class" HeaderText="班級" />
</Columns>
</asp:GridView>
protected void ckbSelect_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow)cb.NamingContainer;
if (cb.Checked)
row.BackColor = System.Drawing.Color.FromName("#e2eaec"); // 高亮色
else
row.BackColor = System.Drawing.Color.Empty; // 恢復預設
}
上述代碼僅處理觸發事件的那一行,無需迴圈遍歷整個 GridView,效能更佳。若需「全選/反選」功能,另加標題列 CheckBox:
<HeaderTemplate>
<asp:CheckBox ID="ckbSelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="ckbSelectAll_CheckedChanged" />
</HeaderTemplate>
protected void ckbSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox cbAll = (CheckBox)sender;
foreach (GridViewRow row in gvStudent.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("ckbSelect");
cb.Checked = cbAll.Checked;
row.BackColor = cbAll.Checked ? Color.FromName("#e2eaec") : Color.Empty;
}
}
ViewState 或 Session 儲存選中鍵值集合 (HashSet<int>)。PageIndexChanging 事件中重新綁定後,根據集合恢復 CheckBox 狀態與行顏色。純前端實現,配合 :has() 偽類(現代瀏覽器支援):
<style>
.gv-row { transition: background-color 0.2s; }
.gv-row:has(input[type=checkbox]:checked) { background-color: #e2eaec; }
</style>
需移除 AutoPostBack,適合純前端選中收集場景。
AutoPostBack=true + OnCheckedChanged。NamingContainer 定位行,直接設 BackColor。此技巧廣泛應用於批量刪除、匯出、狀態變更等列表操作場景。