要做這效果, 分為兩大項
- 取得該button所在的Row或取得Row Index
- 取得該Row的各Cell資料
protected void Button1_Click(object sender, System.EventArgs e) { //Get the button that raised the event Button btn = (Button)sender; //Get the row that contains this button GridViewRow gvr =(GridViewRow)btn.NamingContainer;
}
重點在於先sender轉型成button, 在利用.NamingContainer實作該row
如果想要取得Row Index, 則用「int rowindex = gvr.RowIndex;」
2.取得該Row中的指定Cell資料
單純文字: gvr.Cells[0].Text;
使用Template的特定控制項:gvr.FindControl("Button1");
可用的方法還挺多的(這裡此論CodeBehind), 上面是最簡單的方法
以下就來作補充說明
資料來源:Get GridView RowIndex upon button click
除了用「Click」事件外另外有「Command」及「SelectedIndexChange」這兩種常用的事件
取得方法都不太一樣
「Command」事件(適合用在性質相似但功能略有不同的控制項)
這是先取得Row Index, 再取得Row
要使用這事件,必須要在html中設定「CommandName」及「CommandArgument」
- CommandName:隨喜好設定
- CommandArgument:<%# Container.DataItemIndex %>
接下來到*.cs中轉寫function
protected void Expo_Command(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e) { if (e.CommandName == "forCSR") { //Get rowindex int rowindex =Convert.ToInt32(e.CommandArgument); //Get Row GridViewRow gvr = GridView1.Rows[rowindex]; } }「SelectedIndexChange」事件
不外乎是使用「.NamingContainer」
DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e) { //Get the dropdownlist that raised the event DropDownList ddl = (DropDownList)sender; //Get the row that contains this dropdown GridViewRow gvr = (GridViewRow)ddl.NamingContainer; //Get rowindex int rowindex = gvr.RowIndex; } 延伸閱讀:
Q:「RowIndex」和「DataItemIndex」有什麼差別?
A:都可以用來取得GridView中的index
差別在於RowIndex是每頁分開算(一律從 0 ~ n 的相對index)
而DataItemIndex則是位於Binding中的絕對index
資料來源:What is difference between RowIndex and DataItemIndex?
NamingContainer取得 GridView的列數(RowIndex)、對應的資料表 這一列的主索引鍵
GridView RowCommand 事件
沒有留言:
張貼留言