ASP.NET - Auto Generate Row Number in GridView C#


In the previous articles I explained about Export Gridview to Excel - Asp.Net, C# - Remove Columns that contains null values in Data Table, How to export web page as PDF with Image? - itextsharp etc.

In this article I will explain a simple way to display row numbers in Asp.Net data bound controls. Find the asp web form example below:-


GridView
  •   You can do using Container.DataItemIndex in GridView
<asp:TemplateField HeaderText="Serial No">                   
                    <ItemTemplate>
                        <%#Container.DataItemIndex + 1 %>
                    </ItemTemplate>
</asp:TemplateField>

C# - Simple ways to Auto Generate Serial Number in GridView - An Example
  • You can add following line of code to auto generate a column in GridView
  <asp:TemplateField HeaderText="Serial No">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server"
                        Text='<%# (GridView1.PageSize * GridView1.PageIndex) + Container.DisplayIndex + 1 %>'>
                        </asp:Label>
                    </ItemTemplate>
</asp:TemplateField>

Repeater
<asp:Repeater ID="Repeater1" runat="server">
                <ItemTemplate>
                    <%#Container.ItemIndex+1 %>
                </ItemTemplate>

</asp:Repeater>

DataList
            <asp:DataList ID="DataList1" runat="server">
                <ItemTemplate>
                    <%#Container.ItemIndex+1 %>
                </ItemTemplate>

            </asp:DataList>

DetailsView
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px">
                <Fields>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <%#Container.DataItemIndex+1 %>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Fields>

            </asp:DetailsView>

FormView
<asp:FormView ID="FormView1" runat="server">
                <ItemTemplate>
                    <%#Container.DataItemIndex+1 %>
                </ItemTemplate>

            </asp:FormView>

ListView
<asp:ListView ID="ListView1" runat="server">
                <ItemTemplate>
                    <%#Container.DataItemIndex+1 %>
                </ItemTemplate>

            </asp:ListView>

Download the source code click here ..
Please leave your comments, suggestions and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading .. :)

Post a Comment

 
Top