Adding the row number to an ASP.NET GridView

I often want my GridViews to have the first column just be a number identifying the row. I see this beneficial because:

  • The user can see the number of rows returned by scrolling to the end of the GridView
  • If there are two people looking at the GridView, they can say “look at item #5 …”

image

To make this happen you need to add this element to the <columns> element of your GridView:

 
<asp:GridView ...>
    <Columns> 
        <asp:TemplateField> 
            <ItemTemplate> 
                <%# Container.DataItemIndex + 1 %>. 
            </ItemTemplate> 
            <ItemStyle HorizontalAlign="Right" /> 
        </asp:TemplateField> 
        ... 
    </Columns> 
    ... 
</asp:GridView>	

This looks weird if paging is on. But you can tweak the math to make it work right.

Advertisements

3 thoughts on “Adding the row number to an ASP.NET GridView

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 )

Google+ photo

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

Connecting to %s