Programming Tutorials

How to Add an Auto-Incrementing Serial Number to ASP.NET GridView (C#)

Introduction

This tutorial explains how to add an automatically increasing serial-number column (S.No.) to an ASP.NET GridView using C#. The number starts at 1 on the first page and continues across pages when the GridView uses its standard paging behaviour.

Scope: This example is for ASP.NET Web Forms on the .NET Framework, using the System.Web.UI.WebControls.GridView control. It is not an ASP.NET Core MVC, Razor Pages or Blazor example.

Advertisement

Step 1: Add a TemplateField for the serial number

Open the GridView markup in your .aspx page. Inside its <Columns> element, add a TemplateField containing a Label control. The Label will display the calculated number for each data row.

<asp:TemplateField HeaderText="S.No">
    <ItemStyle HorizontalAlign="Center" />
    <ItemTemplate>
        <asp:Label ID="lblSerialNo" runat="server" />
    </ItemTemplate>
</asp:TemplateField>

Keep the existing data columns in the GridView. Place the serial-number TemplateField where you want the S.No. column to appear.

Advertisement

Grisview ASP

Step 2: Connect the GridView to the RowDataBound event

Add the OnRowDataBound attribute to the GridView. This event runs as each row is bound to its data record, allowing you to find the Label inside the row and set its text.

<asp:GridView
    ID="GridView1"
    runat="server"
    AutoGenerateColumns="False"
    AllowPaging="True"
    PageSize="15"
    OnRowDataBound="GridView1_RowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="S.No">
            <ItemStyle HorizontalAlign="Center" />
            <ItemTemplate>
                <asp:Label ID="lblSerialNo" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>

        <!-- Add your existing BoundField or TemplateField columns here. -->
    </Columns>
</asp:GridView>

This is the relevant part of the GridView declaration; keep your existing data source, styling and data columns. The sample uses a page size of 15, matching the original example. If you use DataKeyNames, make sure it names a real key field in your data source. It is not required just to display a serial number.

Step 3: Add the C# RowDataBound event handler

In the page’s code-behind file (for example, Default.aspx.cs), make sure the Web Forms controls namespace is available:

using System.Web.UI.WebControls;

Add this event handler inside your page class:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // Set the number only for data rows, not the header, footer or pager.
    if (e.Row.RowType != DataControlRowType.DataRow)
    {
        return;
    }

    Label lblSerial = e.Row.FindControl("lblSerialNo") as Label;

    // Avoid a null-reference error if the Label is missing from the template.
    if (lblSerial == null)
    {
        return;
    }

    int serialNumber =
        (GridView1.PageIndex * GridView1.PageSize) + e.Row.RowIndex + 1;

    lblSerial.Text = serialNumber.ToString();
}

Check that the event name in the markup, GridView1_RowDataBound, matches the method name in the code-behind. Also make sure the Label ID is exactly lblSerialNo in both places.

How the serial-number formula works

The calculation is:

Serial number = (PageIndex × PageSize) + RowIndex + 1

  • PageIndex is the current page number starting from zero. The first page has index 0; the second page has index 1.
  • PageSize is the maximum number of data rows displayed on each page. In this example it is 15.
  • RowIndex is the zero-based position of the data row on the current page. The first data row has index 0.
  • + 1 converts the zero-based calculation into a human-readable serial number beginning at 1.

Worked example with 15 rows per page

GridView page PageIndex First row number Last row number (if full)
Page 1 0 1 15
Page 2 1 16 30
Page 3 2 31 45

For example, on page 2 the first data row has PageIndex = 1, PageSize = 15 and RowIndex = 0. The result is (1 × 15) + 0 + 1 = 16.

If you want the serial number to restart on every page

Some tables should show 1, 2, 3 and so on on every page rather than continuing the count. In that case, use the row index alone:

lblSerial.Text = (e.Row.RowIndex + 1).ToString();

Use the full formula from Step 3 when you want numbering to continue across standard GridView pages.

Important notes about paging, sorting and data binding

  • Standard paging: The page-index formula is intended for a GridView using its normal paging behaviour with a consistent page size.
  • Custom paging: If your data-access layer uses a custom row offset or keyset-paging approach, calculate the number from the actual offset supplied by that layer rather than assuming the control’s page index is the database row offset.
  • Sorting and filtering: The serial number reflects the current displayed order. After sorting or filtering, the numbers are recalculated for the visible result set; they are not permanent database IDs.
  • Data binding: If you bind the GridView manually, do not reset its data and page index on every postback. Bind at the appropriate point in the page lifecycle and preserve the selected page when handling paging.
  • Other row types: The handler checks DataControlRowType.DataRow so it does not try to find the Label in header, footer or pager rows.

Optional: Handle paging when binding data manually

If your GridView uses a data source control that handles paging for you, you may not need this event handler. If you load the data in C# yourself, handle PageIndexChanging, set the requested page index and bind the data again. Replace BindGrid() with the method used in your project:

protected void GridView1_PageIndexChanging(
    object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    BindGrid();
}

Wire it up in the GridView markup with OnPageIndexChanging="GridView1_PageIndexChanging". The BindGrid() method is application-specific; it should retrieve the same filtered and sorted result set for the requested page.

Common problems and fixes

  • The serial-number column is blank: Confirm that OnRowDataBound is connected to the correct method and that the Label ID matches the value passed to FindControl.
  • Every page starts at 1: Check that you are using the formula with GridView1.PageIndex and GridView1.PageSize, not only e.Row.RowIndex.
  • A null-reference error occurs: Check that the Label exists inside the data-row ItemTemplate. The null check in the sample prevents the handler from failing if it is absent.
  • The page number changes but the data does not: If you bind manually, set PageIndex from e.NewPageIndex and call your data-binding method. If you use a data source control, check its paging configuration.
  • The numbers do not match a custom database query: Use the row offset or starting record number calculated by your custom paging logic.

Frequently asked questions

Can I generate a serial number without adding a database column?

Yes. This example calculates the display number while the GridView binds each row. It does not add or modify a column in the database.

Does the serial number continue on the next page?

Yes, when the GridView uses standard paging and the code uses (PageIndex × PageSize) + RowIndex + 1.

Can I use this method with a TemplateField?

Yes. The Label is placed inside a TemplateField’s ItemTemplate, and the RowDataBound event finds it with FindControl.

Is this code for ASP.NET Core?

No. The GridView control shown here belongs to ASP.NET Web Forms on the .NET Framework. ASP.NET Core applications use different UI patterns and do not include the Web Forms GridView server control.

Conclusion

You can add an automatic S.No. column to an ASP.NET Web Forms GridView by placing a Label inside a TemplateField and setting its value in the RowDataBound event. For standard paging, combining PageIndex, PageSize and RowIndex keeps the numbering continuous across pages. Choose the page-local formula instead if every page should start again at 1.

Related ASP.NET C# tutorial

Official Microsoft references

RochakGuy

Hi, I'm Piyush and I'm a passionate blogger. I love sharing my insights on Rochaksite.com. I'm committed to providing practical and informative content that helps readers achieve their goals and make informed decisions. When I'm not writing, I enjoy exploring new topics and trends in Technology and indulging in my personal hobbies and interests.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button