各位好!
现有一个关于GridView的问题要请教下大家:
我用GridView绑定了一些数据,没有将数据源执行分页操作,数据源是ObjectDataSource,直接用的GridView的分页功能,每页显示5条信息,我在GridView中添加了一个模版列,是ImageButton,名称是cmdAdd,用于执行GridView的RowCommand事件的,用ImageButton的CommandArgument绑定了当前数据行的行索引,然后在GridView的RowCommand事件中写到:protected void gvIO_RowCommand(object sender, GridViewCommandEventArgs e)
    {
if (e.CommandName == "cmdAdd")
        {
            int rowIndex = int.Parse(e.CommandArgument.ToString());
            GridViewRow row = (sender as GridView).Rows[rowIndex];
            
            //其他相关的操作,可以不用管
            string DN = Request.QueryString["DN"].ToString();
            string IONumber = (row.FindControl("lblIONumber") as Label).Text;
            string CustomerProductNumber = (row.FindControl("lblCustomerProductNumber") as Label).Text;
            string Sufferer = (row.FindControl("lblSufferer") as Label).Text;
            string ProductCode = (row.FindControl("lblProductCode") as Label).Text;
            string Barcode = (row.FindControl("lblBarcode") as Label).Text;
            DNBLL bll = new DNBLL();
            if (bll.AddDetails(DN, IONumber, CustomerProductNumber, Sufferer, ProductCode, Barcode))
            {
                gvMain.DataBind();
                gvIO.DataBind();
            }
        }
}如果当前GridView没有执行翻页操作,这些代码是正常的,但是用GridView的默认按钮执行翻页操作时:
GridViewRow row = (sender as GridView).Rows[rowIndex];
这个就出现错误,好像是提示“索引超出数组的范围”,但我看了rowIndex的值是对,这个问题蛮奇怪的,望各位兄弟帮忙解答下,谢谢了!

解决方案 »

  1.   

      int rowIndex = int.Parse(e.CommandArgument.ToString());
      GridViewRow row = (sender as GridView).Rows[rowIndex];=====  int rowIndex = Convert.ToInt32(e.CommandArgument);   GridViewRow row =gvIO.Rows[rowIndex ];
      

  2.   

    GridViewRow row = (sender as GridView).Rows[rowIndex];
    gridview的row索引从零开始,你绑定的CommandArgument是不是从1开始了
      

  3.   

    中午又想了一下,你的问题应该是你绑定的索引和gridview的索引不一致导致的,gridview每一页的数据,都是从0开始索引的。比如一共十条数据,每页五条数据,那么第二页的第一行数据的索引依然是0开始,而你绑定的是6,所以超出索引了。建议你用如下方法:
    int rowIndex =((GridViewRow)(((LinkButton)(e.CommandSource)).Parent.Parent)).rowindex;
    当然,这里的LinkButton应该替换为你模板列中控件类型,比如button等
    qq:25004370
      

  4.   

    是否未处理分页PageIndexChanging事件
      

  5.   

    可以不用CommandArgument,直接判断ImageButton所在的行号
            if (e.CommandName == "cmdAdd")
            {
                ImageButton iButoon =(ImageButton)e.CommandSource;
                int rowIndex = ((GridViewRow)iButoon.NamingContainer).RowIndex;
                GridViewRow row = (sender as GridView).Rows[rowIndex];
            }
      

  6.   

    谢谢各位的解答,这个问题已解决了,再次谢谢leritt和koukoujiayi的方案都是可以的。结贴了。