Auto-generate serial no for GridView

When there was a need to show a serial no in Gridview on selected datasource then I was doing it in query (SQL Server) using ROW_NUMBER OVER() or RANK OVER(). But in the current project I am working on, needs some GridViews to be populated from XML datasource and some from manipulated/modified datatable. To these scenario I also can include another one, when you need to rows to be sorted in some order by allowing sorting in GridView and data of the to sorted from datatable. So, here I added an ItemTemplate to show the incremental Sl no. column. Following is the code for it.

<asp:TemplateField HeaderText="SL">
<asp:Label ID="lblSlNo" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
<HeaderStyle HorizontalAlign="Center" Width="30px" />
<ItemStyle HorizontalAlign="Center" Width="30px" />

Here the value shown in the Sl no. column will start from the DataItemIndex (which starts from 0)+1 and so on..
Regarding performance, it is faster than former method and is a very convenient way to do so.

7 thoughts on “Auto-generate serial no for GridView

  1. Yes, Suvendu, I am also using that way. It is definitely better than what you are using before this. Anyway thanks for posting it here. I hope more to come from you like this useful article. keep it up.

  2. Hi I have 3 gridviews on the same aspx page and all of them have serial number column but the serial number in the first gridview shows 1 record for 2nd gridview 2 record and for 3rd gridview it shows 3 records.

    • Hi @Priyanka !
      Can you please share the code snippets you have used to show serial no in gridviews?
      Else, please explain a little more so that I’ll be able to help you.

      Thanks !

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s