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"> <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.
Posted on November 26, 2011, in ASP.Net. Bookmark the permalink. 2 Comments.

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.
Thanks, I will definitely post more about datasource controls and their advanced features and properties, so please stay tuned for all the updates..