Serial Number DataGrid Column
Serial Number DataGrid Column
There are times when a serial number column on the datagrid is useful, especially when the datagrid is used to display registration information, order details etc. I’ll be sharing with you how to accomplish this by inheriting from a bound data column. This solution would allow you to add a serial number column into any asp.net’s datagrid control.
Implementation
Because in most scenarios, there will be paging for datagrids, hence we will need two integer properties; CurrentPage and PageSize. CurrentPage is used to inform the control which page the datagrid is at, while PageSize is used to inform the maximum number of records shown in the datagrid. If paging is not enabled in the datagrid, set the two properties to 0.
Next, we would be overriding FormatDataValue method. FormatDataValue converts the specified value to the format indicated by the DataFormatString property. We will override this to print the serial number. Below is the code.
protected override string FormatDataValue(object dataValue)
{
return ((_PageSize * _CurrentPage) + this.Owner.Items.Count + 1).ToString();
}
Usage
I’ll be using an asp.net page in SgDotNet’s Event Management System as an example. This page is used to view and manage registrations for an event. The datagrid is showing the usernames of members registered for the event. You will need to specify a DataField for the bound column to work. Any field in the dataset will do just fine.
<asp:datagrid id="dgRegistrations" runat="server" Width="100%" AllowSorting="True" PageSize="10" OnPageIndexChanged="dgRegistrations_PageIndexChanged" CssClass="Grid" ShowHeader="True" DataKeyField="Username" AutoGenerateColumns="False" HeaderStyle-CssClass="GridHeader" ItemStyle-CssClass="GridBody">
<Columns>
<sgdn:SerialNoColumn PageSize="10" CurrentPage="0" DataField="Username" HeaderText="SN" HeaderStyle-CssClass="AttendanceHeader" ItemStyle-CssClass="AttendanceBody"></sgdn:SerialNoColumn>
<asp:TemplateColumn SortExpression="Username|asc" HeaderText="Username">
<ItemTemplate>
<asp:Label ID="lblUsername" Runat="server">
<%# DataBinder.Eval(Container.DataItem, "Username") %>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</sgdn:SerialNoColumn>
</Columns>
</asp:datagrid>
At the code behind, we need to capture the PageIndexChanged event, and update the CurrentPage property of the control.
private void dgRegistrations_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
((SgDotNet.WebSite.Controls.SerialNoColumn) (this.dgRegistrations.Columns[0])).CurrentPage = e.NewPage;
BindRegistrations();
}
That’s it. This is how it looks like.

The source code is provided here, if you need it..
As usual, please share with me your comments or any other better way of doing things. You might need to have a SgDotNet account to post comments.