客戶端模擬 GridView 列選取:變色反白 + 隱藏欄位回傳鍵值
頁面佈局
<input id="hdnEmailID" type="hidden" value="0" runat="server" />
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvUsers_RowDataBound">
<Columns>
<asp:BoundField DataField="Email" HeaderText="郵件" ReadOnly="True" />
<asp:BoundField DataField="Name" HeaderText="姓名" ReadOnly="True" />
</Columns>
</asp:GridView>
<asp:Button ID="btnSelect" runat="server" OnClick="btnSelect_Click" Text="Select" />
JavaScript 選取邏輯
<script type="text/javascript">
var lastRowSelected, originalColor;
function GridView_selectRow(row, emailID) {
var hdn = document.form1.hdnEmailID;
hdn.value = emailID;
if (lastRowSelected != row) {
if (lastRowSelected != null) {
lastRowSelected.style.backgroundColor = originalColor;
lastRowSelected.style.color = 'Black';
lastRowSelected.style.fontWeight = 'normal';
}
originalColor = row.style.backgroundColor;
row.style.backgroundColor = 'BLACK';
row.style.color = 'White';
row.style.fontWeight = 'normal';
lastRowSelected = row;
}
}
function GridView_mouseHover(row) { row.style.cursor = 'hand'; }
</script>
RowDataBound 註冊事件
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.ID = e.Row.Cells[0].Text; // Email 作為 ID
e.Row.Attributes["onclick"] = "GridView_selectRow(this,'" + e.Row.Cells[0].Text + "')";
e.Row.Attributes["onmouseover"] = "GridView_mouseHover(this)";
}
}
伺服器端取得選中值
protected void btnSelect_Click(object sender, EventArgs e)
{
Response.Write(hdnEmailID.Value); // 取得選中列的 Email
}
優點
- 無 PostBack 即時視覺回饋。
- 隱藏欄位攜帶鍵值,伺服器端按鈕事件直接讀取。
- 相容舊版 GridView,無需 CheckBoxField 或 SelectCommand。