Showing row number in Gridview

Hi,

 

A few days ago some one asked me this in a mail. After thinking on this a bit I decided to make a post as I thought this might be useful to many. Many a times while using a Gridview or a Datagrid we want to show a row number along with the Row, so that its easy for the user. The row number should always start from 1 no matter what the sorting is.

 

This can be done in many ways. We can fetch a record from the database itself using the identity column. But this small problem does not needs such a complex solution. It can easily be solved in the Gridview or Datagrid itself. What we need to do is add a new template column to the Gridview (I ma using Gridview’s example to do this same cane be done with Datagrid, datalist etc.). And in the template column add a new label. Now bind the label in the rowdatabound event. Here is a code snippet for the same in the rowdatabound event

if (e.Row.RowType == DataControlRowType.DataRow)
{
     Label lableIndex;
     int i = e.Row.RowIndex + 1;
     lableIndex = e.Row.FindControl("lableIndex ");
     lableIndex.Text = i.ToString();
}

That’s all, this will show a running number of the row no matter what the sorting is in the Gridview.

 

Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 9/4/2008 3:20:51

Very nice! However I am generating a dataview dynamically and cannot use a template. Also need to show start-end row numbers for a subset paged on the back end. What I am trying to do is add a column with a sequence of m-n row numbers after the view is sorted, using VB code. Is there a way to get the dataview to actually apply the sort so the rows are in the order they will display? Any other suggesions?

Posted on 12/18/2008 9:00:39 AM

This works fine for the first page, but the numbers restart at 1 when you click on other pages. Do you know of a way to continue the count through all pages of the gridview?

Posted on 12/18/2008 9:04:38

Hi Neal,

All you need to do is keep a int variable in the page level, which will contain the starting point of index. In the page index changed event set this variable to value of NewPageindex * number of record per page.

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2009 Vikram Lakhotia