获取GridView中RowCommand的当前索引行

本文介绍如何在 ASP.NET 的 GridView 控件中使用 Button 和 LinkButton 控件触发特定的 RowCommand 事件,并展示了如何通过 CommandName 属性来区分不同的按钮点击事件,以及如何获取被点击行的数据索引。
前台添加一模版列,里面添加一个Button
<asp:TemplateField HeaderText="测试">
      
<ItemTemplate>
           
<asp:Button ID="Button1" CommandName="btn" runat="server" Style="position: relative" Text="Button" />
      
</ItemTemplate>
</asp:TemplateField>


后台

protected void gv_Company_RowCommand(object sender, GridViewCommandEventArgs e){
        
if (e.CommandName == "btn"){
            i
nt index = Convert.ToInt32(e.CommandArgument);
            DataKey key 
= this.gv_Company.DataKeys[index];
            
string str = key.Value.ToString();
        }

    }


    
//行数据绑定
    protected void gv_Company_RowDataBound(object sender, GridViewRowEventArgs e){
        
if (e.Row.RowType == DataControlRowType.DataRow){
            Button bt 
= new Button();
            bt 
= (Button)e.Row.Cells[6].FindControl("Button1");
            bt.CommandArgument 
= e.Row.RowIndex.ToString();
        }

    }



    那么,如果是在GridView里已经设置了LinkButton为事件处理按钮,将通过以下方法获取索引
protected void gv_Company_RowCommand(object sender, GridViewCommandEventArgs e){
        
if (e.CommandName == "btn"){        
              GridViewRow drv = ((GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent));
              object result = (object)gv_Company.DataKeys[drv.RowIndex][int];//int为DataKeys位置
        }

    }


转载于:https://www.cnblogs.com/ke7in/archive/2008/07/17/1245029.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值