Telerik's ASP.NET AJAX RadGrid with Custom Paging and Sorting

To improve the page speed and reducing the large data handling load on the server we usually need to implement custom Paging and Sorting. Today I am going to tell how this can be done with RadGrid.

Step 1: Add "AllowPaging='True'" and  "AllowCustomPaging='True'" for enabling custom paging & "AllowSorting='true' "AllowCustomSorting='True'" for enabling custom sorting, attributes to the RadGrid element.

Step 2: We specified to the RadGrid control that we are handling paging and sorting on our own. Now we need to register an event i.e. "OnNeedDataSource". Your RadGrid will look like below:

<telerik:RadGrid runat="server" ID="RgProducts" 
    AllowSorting="true" AllowCustomSorting="True"
    AllowPaging="True" AllowCustomPaging="True" VirtualItemCount="1000"
    OnNeedDataSource="RgProducts_OnNeedDataSource" OnSortCommand="RgProducts_OnSortCommand">
    <MasterTableView TableLayout="Fixed"></MasterTableView>

Step 3: Its time to write backend logic for applying custom paging and sorting. You:

protected void RgProducts_OnNeedDataSource(object sender, GridNeedDataSourceEventArgs e)
	var sortByColumn = "Id";
	var sortByDirection = "ASC";
	if (RgProducts.MasterTableView.SortExpressions.Count > 0)
		var sortExpression = RgProducts.MasterTableView.SortExpressions[0];
		sortByColumn = sortExpression.FieldName;
		sortByDirection = sortExpression.SortOrderAsString();
	var pageSize = RgProducts.PageSize;
	var startRowIndex = RgProducts.CurrentPageIndex * pageSize;
	var sortExp = string.Format("{0} {1}", sortByColumn, sortByDirection);
	RgProducts.VirtualItemCount = Repository.Instance.Products.Count();  //For letting the grid know how many items are there.
	RgProducts.DataSource = Repository.Instance.Products.OrderBy(sortExp) // This OrderBy is a method of open source library: