如何在GridView的RowCommand事件中获取当前的GridViewRow

本文介绍了如何在GridView的RowCommand事件中获取当前的GridViewRow。常见方法是通过CommandArgument绑定RowIndex,但也可以利用控件层次和事件参数,如sender和NamingContainer/BindingContainer来实现。
摘要由CSDN通过智能技术生成
 由于事件参数 GridViewCommandEventArgs 并不公开Row属性指示当前行,(DataGridCommandEventArgs 公开 Item 属性以获取当前 DataGridItem,不知 ASP.NET Team 是如何考虑这一设计的),因此需要一点“技巧”来获取此属性。

其实这是一个早就已知的问题,鉴于CSDN里面每每有人疑惑,这里稍微整理下,便于参考。

至少有三种方法可以使用,其中给 CommandArgument 绑定 RowIndex 是最常见的方法,也是 MSDN 提供的,然而实际上只需要充分利用控件层次与事件参数就足够可以回溯出来:sender 与 NamingContainer/BindingContainer,具体见代码。

 

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int rowIndex = -1;
        GridViewRow row = null;        
        switch (e.CommandName) {
            case "Command1": // 模板列
                // 对于模板列内的按钮,我们需要显示绑定行索引到按钮的 CommandArgument 属性
                // 以获取触发事件的行信息
                rowIndex = Convert.ToInt32(e.CommandArgument);
                row = GridView1.Rows[rowIndex];                
                DisplayInfo(row, e.CommandName);
                // your codes
                // 
                break;
            case "Command2": // 模板列
                // 同样处于模板列中,但不采用 Command1 方式,而是通过 NamingContrainer 属性
                // 直接获取当前的 GridViewRow
                Control cmdControl = e.CommandSource as Control; // 表示触发事件的 IButtonControl,保持统一性并便于后续操作,我们这里直接转化为控件基类 Control
                row = cmdControl.NamingContainer as GridViewRow;
                DisplayInfo(row, e.CommandName);
                // your codes
                // 
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值