we are going to see how to generate sequence number (row number) in DataGrid.
To generate sequence number, we will use the DataGridItem’s ItemIndex property.
But For example if we are going to second page with Pagesize 3, then sequence
number should start from 4. Code snippet for implementing this method is...
<asp:DataGrid id="DataGrid1" runat="server" PagerStyle-Mode="NumericPages"
PageSize="10" AutoGenerateColumns="False" AllowPaging="True">
<Columns>
<asp:templatecolumn headertext="Row Number">
<itemtemplate>
<%# (DataGrid1.PageSize*DataGrid1.CurrentPageIndex)+ Container.ItemIndex+1%>
</itemtemplate>
</asp:templatecolumn>
<asp:boundcolumn runat="server" DataField="CompanyName" HeaderText="Company Name">
</asp:boundcolumn>
<asp:boundcolumn runat="server" DataField="Address" HeaderText="Address">
</asp:boundcolumn>
</Columns>
</asp:DataGrid>
Sample code as such is very simple, we will create one extra template column in
our DataGrid and bind to it the value of Container.ItemIndex. The itemindex
property is zero based so we will add one to it to start from one.
The code is very simple, instead of only using container.itemindex to get the
sequence number. You need to use Pagesize and currentpageindex to find out the
starting number of that page and then add container.itemindex to that.
So we have sequence number in DataGrid. DataGrid will look like this,
Number Name Address
------------------------------
1 Ashvin Bombay
2 Kamlesh S Delhi
3 Hiren Pune
------------------------------
Paging : 1 2 3 4 5
------------------------------
Note: you can also get this result from SQL Query, follow this query to get auto number column in Result.
select
ROW_NUMBER() OVER(ORDER BY Associate DESC) AS 'Number',
Name,
Address
from dbo.Contact
Result for this Query
---------------------
Number Name Address
------------------------------
1 Ashvin Bombay
2 Kamlesh S Delhi
3 Hiren Pune
Comments