Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get row index of second page of gridview

I have taken a GridView with paging having pagesize=10 but when i move to second page & select 1st row of it then it shows the index as 11 despite 0 So please tell me how to resolve it.

Here is what i tried so far:

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 
}

When i try it for 11th row it throw error as:

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

if i mannually pass the value to index=0 it works.

like image 206
AVINASH BHALKE Avatar asked Dec 19 '22 06:12

AVINASH BHALKE


2 Answers

Say your datasoure returns 100 results. So a unique DataItemIndex will be assigned to your CommandArgument from 0 to 99. Now if you have set PageSize = 10 for your gridview, at a time only 10 rows will be visible. Say now you move to page 3 and click 3rd record the DataItemIndex will be 22 while your GridView has 10 rows visible and so index goes out of range.

int rowindex = Convert.ToInt32(e.CommandArgument) % GridView1.PageSize;
GridViewRow row = GridView1.Rows[rowindex];
like image 89
Mahesh Avatar answered Jan 06 '23 13:01

Mahesh


// 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);
}
like image 33
Luis Picado Avatar answered Jan 06 '23 13:01

Luis Picado