【问题标题】:Get row index of second page of gridview获取gridview第二页的行索引
【发布时间】:2018-09-19 17:15:38
【问题描述】:

我已经使用了带有 pagesize=10 的分页的 GridView,但是当我移动到第二页并选择它的第一行时,尽管索引为 0,但它显示索引为 11 所以请告诉我如何解决它。

这是我目前尝试过的:

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
      GridView1.PageIndex = e.NewPageIndex;
      BindGrid();
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
     int index = (Convert.ToInt32(e.CommandArgument));
     GridViewRow row = GridView1.Rows[index];
     //Some operation 
}

当我尝试第 11 行时,它会抛出错误:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

如果我手动将值传递给 index=0 它可以工作。

【问题讨论】:

    标签: c# asp.net gridview


    【解决方案1】:

    假设您的数据源返回 100 个结果。所以一个唯一的DataItemIndex 将被分配给你的CommandArgument,从 0 到 99。 现在,如果您为gridview 设置了PageSize = 10,一次只能看到10 行。 现在假设您移动到第 3 页并单击第 3 条记录,DataItemIndex 将为 22,而您的 GridView 有 10 行可见,因此索引超出范围。

    int rowindex = Convert.ToInt32(e.CommandArgument) % GridView1.PageSize;
    GridViewRow row = GridView1.Rows[rowindex];
    

    【讨论】:

      【解决方案2】:
      // Convierte el numero almacenado en CommandArgument a int para sacar el index
      // Converts the number stored in CommandArgument to int to remove the index
      int index = Convert.ToInt32(e.CommandArgument);
      
      // Convierte el PageIndex del GridView a int
      // Convert the PageIndex of the GridView to int
      int pageIndex = Convert.ToInt32(gv_Comentarios.PageIndex);
      
      // Convierte al index en la verdadera posicion del dataset
      // It becomes the true position of the dataset to the index
      if (pageIndex > 0)
      {
          index = index + (pageIndex * 10);
      }
      

      【讨论】:

        猜你喜欢
        • 2013-06-27
        • 2012-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-15
        • 1970-01-01
        • 2010-10-02
        相关资源
        最近更新 更多