在页脚模板中从链接按钮获取行索引

3

我对Gridview的这个问题感到沮丧。

当位于页脚行中的链接按钮被点击时,我希望在gridview的RowCommand事件中获取行索引。

但我总是得到-1作为index的值。

        Control ctl = e.CommandSource as Control;
        GridViewRow CurrentRow = ctl.NamingContainer as GridViewRow;
        int index = CurrentRow.RowIndex;

如何解决这个问题?

需要页脚行的索引吗? - Bharadwaj
你能否为 LinkButton 添加 OnClick 事件,并使用 ((GridViewRow)((LinkButton)sender).NamingContainer).RowIndex 查找索引? - Bharadwaj
但我想在GridView的RowCommand事件中获取值。 - Mudassir Hasan
那么你可以添加 CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" 并通过 e.CommandArgument 找到索引。 - Bharadwaj
页脚行不是总在底部吗?因此,您无法通过获取Rows.count来确定索引吗? - Pseudonym
显示剩余3条评论
1个回答

1
据我所知,页脚行的RowIndex始终为-1。我已经尝试了一些测试,您也可以尝试一下,对于每一行DataRow类型,我们都会有一个RowIndex,但是对于页脚行,我们将始终具有-1值。下面是我的测试代码(仅供参考,某些代码行不需要)。
protected void grdGrid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            Control ctl = e.CommandSource as Control;
            GridViewRow CurrentRow = ctl.NamingContainer as GridViewRow;
            int index;

            foreach (GridViewRow row in grdGrid.Rows)
            {
                if (CurrentRow.RowType == DataControlRowType.DataRow)
                {
                    //you'll have an RowIndex for each DataRow: 0,1,2 and so on
                    index = CurrentRow.RowIndex;
                }
                else if (CurrentRow.RowType == DataControlRowType.Footer)
                    {
                        //the RowIndex will be always -1 
                        index = CurrentRow.RowIndex;
                    }

            }
        }

我希望这能帮到你。


没问题。祝你好运! - Cosmin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接