ASP.NET 的 GridView 沒有原生的單選樣式,實務上常用「每列放一個 CheckBox,再靠 JavaScript 保證只能勾一個」來模擬 RadioButton 的效果,同時搭配背景色變化提升可用性。
/// <summary>
/// 資料行繫結事件
/// </summary>
protected void gvProduct_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow row = e.Row;
CheckBox ckb = row.Cells[0].FindControl("ckb") as CheckBox;
Label ProductID = row.Cells[0].FindControl("lblProductID") as Label;
row.Attributes.Add("onmouseover", "this.style.backgroundColor='#00A9FF'");
row.Attributes.Add("onmouseout", "gvProducts_onmouseout('" + gvProducts.ClientID + "','" + ckb.ClientID + "',this)");
row.Attributes.Add("onclick", "SelectRadio('" + gvProducts.ClientID + "','" + ckb.ClientID + "','" + ProductID.Text + "',this)");
ckb.Attributes.Add("onclick", "SelectRadio('" + gvProducts.ClientID + "','" + ckb.ClientID + "','" + ProductID.Text + "',document.getElementById('" + row.ClientID + "'))");
}
}
catch (Exception ex)
{
}
}
滑鼠移入直接寫 inline style,移出與點擊則呼叫前端函式,並把 GridView 的 ClientID、CheckBox 的 ClientID 與資料主鍵一併帶過去。
// 滑鼠移出時設定列顏色
function gvUsers_onmouseout(listId, SelectRadioID, row) {
var SelectRadio = document.getElementById(SelectRadioID);
var GridViewtableSearchList = document.getElementById(listId);
var objs = GridViewtableSearchList.getElementsByTagName("input");
for (var i = 0; i < objs.length; i++) {
if (objs[i].type.toLowerCase() == "checkbox" && objs[i] == SelectRadio) {
if (SelectRadio.checked) {
row.style.backgroundColor = '#33A922'; // 選中列
} else {
if (i % 2 == 0) row.style.backgroundColor = '#FFFFFF'; // 交替列
else row.style.backgroundColor = '#F4FAFD';
}
}
}
}
// 滑鼠點擊時使用
function SelectRadio(listId, SelectRadioID, rv, row) {
var SelectRadio = document.getElementById(SelectRadioID);
var GridViewtableSearchList = document.getElementById(listId);
var objs = GridViewtableSearchList.getElementsByTagName("input");
for (var i = 0; i < objs.length; i++) {
// 把除目前列以外的所有 checkbox 取消勾選並還原交替色
if (objs[i].type.toLowerCase() == "checkbox" && objs[i] != SelectRadio) {
objs[i].checked = false;
if (i % 2 == 0) objs[i].parentElement.parentElement.style.backgroundColor = '#FFFFFF';
else objs[i].parentElement.parentElement.style.backgroundColor = '#F4FAFD';
}
}
SelectRadio.checked = !SelectRadio.checked;
// 設定目前列的顏色並回傳主鍵
if (SelectRadio.checked) {
row.style.backgroundColor = '#33A922';
window.returnValue = rv;
} else {
window.returnValue = "";
}
}
整體思路是:遍歷 GridView 底下所有 input,把不是目前點擊的那個 checkbox 一律取消勾選並還原底色,再把目前列設為選中色,同時透過 window.returnValue 把主鍵帶出去給呼叫端使用。
幾個可以強化的地方:catch (Exception ex) {} 把例外吞掉了,除錯時會很痛苦,建議至少記 log;另外用 i % 2 判斷交替色其實是多餘的,GridView 本身就有 AlternatingRowStyle,改用 CSS class 切換會比直接操作 style 好維護得多。