GridView 是 ASP.NET 2.0 最常用的資料呈現控制項,透過 RowDataBound 事件註冊客戶端 JavaScript 事件,可輕鬆實現滑鼠懸停列高亮、點擊選取變色等互動效果,大幅提升使用者體驗。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// 僅處理資料列
if (e.Row.RowType != DataControlRowType.DataRow) return;
// 1. 條件式資料列背景色(業務邏輯高亮)
int money = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "MONEY"));
if (money == 77)
e.Row.BackColor = System.Drawing.Color.Red;
string customer = DataBinder.Eval(e.Row.DataItem, "CUSTOMER").ToString();
if (customer == "sdf")
e.Row.BackColor = System.Drawing.Color.Red;
// 2. 滑鼠懸停高亮:保存原背景色 → 設為黃色
e.Row.Attributes.Add("onmouseover",
"currentcolor=this.style.backgroundColor; this.style.backgroundColor='yellow'; this.style.fontWeight='bold';");
// 3. 滑鼠移出還原:恢復保存的背景色
e.Row.Attributes.Add("onmouseout",
"this.style.backgroundColor=currentcolor; this.style.fontWeight='normal';");
// 4. 點擊列選取:設定綠色背景、文字色、游標
e.Row.Attributes.Add("onclick",
"this.style.backgroundColor='#99cc00'; this.style.color='buttontext'; this.style.cursor='default';");
// 5. 可選:游標變手型提示可點擊
e.Row.Style.Add("cursor", "pointer");
}
DataBinder.Eval(e.Row.DataItem, "欄位名"):晚期繫結取值,回傳 object。Convert.ToInt32、ToString() 型別轉換。e.Row.Attributes.Add("onmouseover", "js code"):輸出至產生的 <tr> 標記屬性。currentcolor 暫存原背景色(全域變數,同頁多列共用,單頁單 GridView 通常無衝突)。e.Row.BackColor:伺服器端設定,輸出 style="background-color:Red;"。e.Row.Style.Add("cursor", "pointer"):直接操作 Style 集合。// 使用閉包或 data-* 屬性儲存原背景色
e.Row.Attributes.Add("onmouseover",
"this.dataset.originalBg = this.style.backgroundColor; this.style.backgroundColor='yellow';");
e.Row.Attributes.Add("onmouseout",
"this.style.backgroundColor = this.dataset.originalBg || '';");
HTML5 dataset 提供元素級儲存,避免多 GridView 或巢狀列表變數污染。
分離結構與行為,維護性更佳:
<style>
.gv-row-hover { background-color: yellow !important; font-weight: bold; }
.gv-row-selected { background-color: #99cc00 !important; color: buttontext; }
.gv-row-pointer { cursor: pointer; }
</style>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.CssClass = "gv-row-pointer";
e.Row.Attributes.Add("onmouseover", "this.classList.add('gv-row-hover');");
e.Row.Attributes.Add("onmouseout", "this.classList.remove('gv-row-hover');");
e.Row.Attributes.Add("onclick", "this.classList.toggle('gv-row-selected');");
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnRowDataBound="GridView1_RowDataBound" DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="CUSTOMER" HeaderText="客戶" />
<asp:BoundField DataField="MONEY" HeaderText="金額" />
</Columns>
</asp:GridView>
RowDataBound 會為每一列觸發,大量資料時注意效能。AllowPaging/AllowSorting,分頁/排序後會重新觸發 RowDataBound,自動套用效果。DataKeyNames 可在點擊事件中取得主鍵值進行進一步處理(如彈出明細視窗)。幾行程式碼即可賦予 GridView 專業級互動體驗,是 ASP.NET 2.0 Web Forms 開發的必備技巧。