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"> <ItemTemplate> <asp:Label ID="lblSlNo" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label> </ItemTemplate> <HeaderStyle HorizontalAlign="Center" Width="30px" /> <ItemStyle HorizontalAlign="Center" Width="30px" /> </asp:TemplateField>
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.