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.

About these ads

About Suvendu

My focused area of learning are ASP.Net, SQL Server, Javascript, Telerik, HTML, CSS ,MVC architecture etc. My areas of interest includes Windows Phone development, Silverlight etc. Blogging and sharing knowledge is my passion. I blog regularly at https://suvendugiri.wordpress.com/

Posted on November 26, 2011, in ASP.Net. Bookmark the permalink. 2 Comments.

  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.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: