- 獲取GridView中RowCommand的當前索引行?前臺添加一模版列,里面添加一個LinkButton
- 前臺?(如果在后臺代碼中用e.CommandArgument取值的話前臺代碼就必須在按鈕中設置CommandArgument的值,值為綁定的數據庫字段
- <asp:TemplateField?HeaderText="操作">
- ????<ItemTemplate>
- ????????<asp:LinkButton?ID="LinkButton1"?runat="server"?CommandName="QianRu"?
- ????????CommandArgument='<%#?Eval("Id")?%>'>簽入</asp:LinkButton>??
- ????????<asp:LinkButton?ID="LinkButton2"?runat="server"?CommandName="QianChu">簽出</asp:LinkButton>
- ????</ItemTemplate>
- </asp:TemplateField>
- 后臺
- 在GridView里已經設置了LinkButton為事件處理按鈕,將通過以下方法獲取索引
- protected?void?gv_Company_RowCommand(object?sender,?GridViewCommandEventArgs?e){
- ????????if?(e.CommandName?==?"QianRu")
- ????{?????//取ID的值方法一???
- ??????????????GridViewRow?drv?=?((GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent));?//此得出的值是表示那行被選中的索引值
- ??????????????inf?id=Convert.ToInt32(GridView1.DataKeys[drv.RowIndex].Value);?//此獲取的值為GridView中綁定數據庫中的主鍵值
- ??????????//取ID的值方法二???
- ??????????????GridViewRow?drv?=?((GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent));?//此得出的值是表示那行被選中的索引值
- ??????????????//此獲取的值為GridView中綁定數據庫中的主鍵值,取值方法是選中的行中的第一列的值,drv.RowIndex取得是選中行的索引
- ??????????int?id?=?Convert.ToInt32(GridView1.Rows[drv.RowIndex].Cells[0].Text);?
- ??????????//取ID的值方法三??
- ??????????//因為在客戶端中就已經將LinkButton的CommandArgument與主鍵Id給綁定了所以在此可以直接用e.CommandArgument得出主鍵ID的值
- ??????????int?id?=?Convert.ToInt32(e.CommandArgument.ToString());?
-
- //取ID的值方法四
- ??????????//此方法不需在模板列中設置CommandArgument的值
- ??????????string?index=e.CommandArgument.ToString();?//那行被選中,取出選中行的索引
- ??????????int?id=Convert.ToInt32(GridView1.Rows[Convert.ToInt32(index)].Cells[0].Text);
- ????}
- 還有一種就是我們并不需要知道當前點擊的是第幾行,可以用以下方法實現要求:?
- <ItemTemplate>?
- ??????<asp:LinkButton?ID="LinkButton1"?runat="server"?CommandArgument='?<%#?Eval("field1")?%>'?
- ??????CommandName="play"?Text='?<%#?Eval("field2")?%>'>?</asp:LinkButton>?
- </ItemTemplate>?
- 上面這個LinkButton,Text綁定了字段2,?CommandArgument綁定了字段1?
- 那么,?
- protected??void??GridView1_RowCommand(object??sender,??GridViewCommandEventArgs??e)?
- {?
- ????if(e.CommandName="play")
- ????{
- ????????LinkButton?lb?=?(LinkButton)e.CommandSource;?
- ????????string??a??=??lb.Text;//這里可以獲得點擊行字段field2的值?
- ????????string?b?=?e.CommandArgument;//這里可以獲得點擊行字段field1的值
- ????}
- }
- 或:
- 如果是使用模板列,可以把數據的任意一列綁定到按鈕的CommandArgument,如下:?
- <asp:TemplateField>?
- <ItemTemplate>?
- <asp:Button?runat="server"?CommandArgument='<%#?Eval("id")?%>'?Text="Button"?/>?
- </ItemTemplate>?
- </asp:TemplateField>?
- 一般可以綁定到主鍵列,這樣可以在RowCommand通過e.CommandArgument獲取當前行的主鍵,也便于進行其他操作?
- 如果是要獲取行索引,比較麻煩一點,還是那個Button1,在GridView的RowDataBound事件中如下:?
- Button?btn?=?(Button)e.Row.FindControl("Button1");?
- if?(btn?!=?null)?
- {?
- btn.CommandArgument?=?e.Row.RowIndex.ToString();?
- }?
- 這樣就可以在RowCommand中通過?int?rowId=Convert.ToInt32(e.CommandArgument.ToString())?獲取行索引了?
轉載于:https://www.cnblogs.com/juan/archive/2009/03/31/1425928.html