To generate serial number using gridview

This is the code snippet for generating serial number in a gridview

To Generrate Serial Number

To generate a serial number in a gridview there are several procedures and one of the is as follows and this is carried out using foreach loop and the code snippet is as follows

int startPos = 1, endPos = 0, pos = 1, startIndex = 1;
startPos = startIndex;
foreach (GridViewRow item in dgView.Rows)
item.Cells[0].Text = startIndex.ToString();
endPos = startIndex;

Drawbacks of the above code

The above code sometimes proves to be disastrous when there is large number of datas in the grid and thus results in infinite loop operation which makes the execution very slow


The Code below proves to be the best alternative as it can generate serial number to large number of datas and can avoid large number of lines on the Code behind


<asp:TemplateField HeaderText="Sl.No">
<%# Container.DataItemIndex + 1 %></ItemTemplate>

If Paging is Enabled

This snippet displays when the paging is enabled

<asp:TemplateField HeaderText="Sno">
<%# (gvUsers.PageSize*gvUsers.PageIndex)+ Container.DataItemIndex+1 %> </ItemTemplate>


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: