In some occasions you may want to display row numbers in Telerik RadGrid - for example to correlate the grid items when exporting the control's structure to Excel or just for easier navigation/access. The functionality is not built-in in the product, however such layout is achievable with a few lines of code:
- Subscribe to the ItemDataBound event of the grid
- Check whether the currently bound item is GridDataItem
- Extract the ItemIndex of the e.Item instance and display its value in a control residing in GridTemplateColumn's ItemTemplate.
In the example code below the item index is presented in MS Label control which is wrapped in template column:
| ASPX/ASCX |
Copy Code |
|
<rad:RadGrid ID="RadGrid1" DataSourceID="AccessDataSource1" AllowSorting="True" Skin="WinXP" runat="server" Width="95%"> <MasterTableView> <Columns> <rad:GridTemplateColumn UniqueName="TemplateColumn" HeaderText="Row number"> <ItemTemplate> <asp:Label ID="numberLabel" runat="server" Width="30px" /> </ItemTemplate> <HeaderStyle Width="30px" /> </rad:GridTemplateColumn> </Columns> </MasterTableView> </rad:RadGrid> <br /> <asp:AccessDataSource ID="AccessDataSource1" DataFile="~/Grid/Data/Access/Nwind.mdb" SelectCommand="SELECT TOP 10 CustomerID, CompanyName, ContactName, ContactTitle, Address, PostalCode FROM Customers" runat="server"></asp:AccessDataSource> |
And in the code-behind:
| C# |
Copy Code |
|
protected void RadGrid1_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e) { if (e.Item is GridDataItem && e.Item.OwnerTableView.DataSourceID == "AccessDataSource1") { Label lbl = e.Item.FindControl("numberLabel") as Label; lbl.Text = e.Item.ItemIndex + 1; } } |
| VB.NET |
Copy Code |
|
Protected Sub RadGrid1_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.WebControls.GridItemEventArgs) Handles RadGrid1.ItemDataBound If (TypeOf e.Item Is GridDataItem AndAlso e.Item.OwnerTableView.DataSourceID = "AccessDataSource1") Then Dim lbl As Label = CType(e.Item.FindControl("numberLabel"), Label) lbl.Text = e.Item.ItemIndex + 1 End If End Sub |