Telerik Rad Grid Sorting

If you are using Telerik Rad Grid and also need to sort column on column's header click than for your requirement below code will help you surely.

.aspx Code :


<telerik:RadGrid ID="RadGrid1" runat="server" AllowSorting="True" EnableViewState="false" AutoGenerateColumns="False" OnSortCommand="RadGrid1_SortCommand"  OnNeedDataSource="RadGrid1_NeedDataSource">
 <SortingSettings EnableSkinSortStyles="true" />
  <MasterTableView AllowNaturalSort="false" AllowSorting="True" AutoGenerateColumns="False">
    <Columns>
       <telerik:GridBoundColumn DataField="Name" HeaderText="Name"  SortExpression="Name">
       </telerik:GridBoundColumn>

       <telerik:GridBoundColumn DataField="Address" HeaderText="Address"  SortExpression="Address">
       </telerik:GridBoundColumn>
   </Columns>
  </MasterTableView>

</telerik:RadGrid>

Code Behind(.aspx.cs) : 


protected void RadGrid1_SortCommand(object sender, GridSortCommandEventArgs e)
        {
            try
            {
                GridSortExpression sortExpr = new GridSortExpression();
                switch (e.OldSortOrder)
                {
                    case GridSortOrder.None:
                        sortExpr.FieldName = e.SortExpression;
                        sortExpr.SortOrder = GridSortOrder.Descending;

                        e.Item.OwnerTableView.SortExpressions.AddSortExpression(sortExpr);
                        break;
                    case GridSortOrder.Ascending:
                        sortExpr.FieldName = e.SortExpression;
                        sortExpr.SortOrder = gvProgramsContracting.MasterTableView.AllowNaturalSort ? GridSortOrder.None : GridSortOrder.Descending;

                        e.Item.OwnerTableView.SortExpressions.AddSortExpression(sortExpr);
                        break;
                    case GridSortOrder.Descending:
                        sortExpr.FieldName = e.SortExpression;
                        sortExpr.SortOrder = GridSortOrder.Ascending;

                        e.Item.OwnerTableView.SortExpressions.AddSortExpression(sortExpr);
                        break;
                }

                e.Canceled = true;

                e.Item.OwnerTableView.Rebind();
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
        }

Comments

Popular posts from this blog

C# Copy files from one server to another

Export SharePoint Online Group Users to Excel using Powershell