GridView/DataGrid 本身均支援行選擇事件(通過設定Button/LinkButton.CommandName="Selected",並在 SelectedIndexChanged 事件中處理)。
然而,有時候我們希望使用者點擊 GridView/DataGrid 一行中任意位置都可以實現觸發一個事件,並在服務端對此行進行相應處理,現在我們就實現此功能。
實現方式
這裡我們採取的方法有點 "hack" :
通過用戶端 javascript 引發行中隱藏的按鈕(Button/LinkButton 均可以)的 click 事件。
主要代碼
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="ProductName" >
<ItemTemplate>
<%# Eval("ProductName") %>
<asp:Button ID="btnHiddenPostButton" CommandName="HiddenPostButtonCommand" runat="server" Text="HiddenPostButton" style="display:none" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" />
</Columns>
</asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Button btnHiddenPostButton = e.Row.FindControl("btnHiddenPostButton") as Button;
if (btnHiddenPostButton != null) {
e.Row.Attributes["onclick"] = String.Format("javascript:document.getElementById('{0}').click()", btnHiddenPostButton.ClientID);
// 額外樣式定義
e.Row.Attributes["onmouseover"] = "javascript:this.style.background='red'";
e.Row.Attributes["onmouseout"] = "javascript:this.style.background=''";
e.Row.Attributes["style"] = "cursor:pointer";
e.Row.Attributes["title"] = "單擊選擇當前行";
}
// 若希望將隱藏按鈕單獨放於一列,則設定此列隱藏,預留位置 <cellIndex> 表示此列索引
//e.Row.Cells[<cellIndex>].Attributes["style"] = "display:none";
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowIndex = -1;
GridViewRow row = null;
switch (e.CommandName) {
case "HiddenPostButtonCommand": // 模板列
Control cmdControl = e.CommandSource as Control; // 表示觸發事件的 IButtonControl,保持統一性並便於後續操作,我們這裡直接轉化為控制項基類 Control
row = cmdControl.NamingContainer as GridViewRow; // 當前行
// 如何訪問儲存格值
// string txt = row.Cells[0].Text;
// 如何擷取模板列中的 Label
// string lbl = row.FindControl("MyLabelID") as Label;
// 執行更多的自訂動作
//
//
Response.Write(String.Format("GridView Version 當前第 {0} 行:", row.RowIndex + 1));
break;
// case "Command2":
// more cases
//
}
}