Skip to content Skip to sidebar Skip to footer

Cannot Sort Table Headers By Ascending Or Descending

By default the View displays a sorted table which is great but cannot Sort the table columns by clicking on the table headers in ascending or descending order. The header column ar

Solution 1:

Check this Sorting using Jtable example

I see you are not using variable jtSorting for sorting. this gives property with which sorting needs to be done. Try with below code after loading newlist.

SortDirection sortDirection = jtSorting.ToLower().Contains("desc") ? SortDirection.DESC : SortDirection.ASC;
    string sortExpression = sortDirection == SortDirection.DESC ? jtSorting.ToLower().Replace(" desc", "") : jtSorting.ToLower().Contains(" asc") ? jtSorting.ToLower().Replace(" desc", "") : jtSorting;

    if (sortDirection == SortDirection.ASC)
            {
                newlist = newlist.OrderBy(item =>GetPropertyValue(item, sortExpression))).ToList();
            }
            else
            {
                newlist = newlist.OrderByDescending(item =>GetPropertyValue(item, sortExpression))).ToList();
            } 

Add below method -

publicstaticobjectGetPropertyValue(object obj, string propertyName)
    {
        return obj == null ? null : obj.GetType().GetProperty(propertyName).GetValue(obj, null);
    }

Add below enum inside your class -

internal enum SortDirection { ASC, DESC }

Post a Comment for "Cannot Sort Table Headers By Ascending Or Descending"