生活随笔
收集整理的這篇文章主要介紹了
获取GridView中RowCommand的当前选中行的索引或主键Id
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
獲取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")????{???????????????????GridViewRow?drv?=?((GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent));???????????????inf?id=Convert.ToInt32(GridView1.DataKeys[drv.RowIndex].Value);? ????????????????????????GridViewRow?drv?=?((GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent));?????????????????????????int?id?=?Convert.ToInt32(GridView1.Rows[drv.RowIndex].Cells[0].Text);? ??????????????????????????????int?id?=?Convert.ToInt32(e.CommandArgument.ToString());? ????????????????????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;????????string?b?=?e.CommandArgument;????}} 或:如果是使用模板列,可以把數據的任意一列綁定到按鈕的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
總結
以上是生活随笔為你收集整理的获取GridView中RowCommand的当前选中行的索引或主键Id的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。