Display the null date values at bottom of the Grid while perform sorting

17 Feb 20222 minutes to read

By default the null values are displayed at bottom of the Grid row while perform sorting in ascending order. As well as this values are displayed at top of the Grid row while perform sorting with descending order. But you can customize this default order to display the null values at always bottom row of the Grid by using SortComparer property of Column.

In the below code we have displayed the null date values at bottom of the Grid row while sorting the OrderDate column in both ways.

@Html.EJS().Grid("Grid").DataSource((IEnumerable<object>)ViewBag.DataSource).AllowSorting().Columns(col =>
{
   col.Field("OrderID").HeaderText("Order ID").Width("100").Add();
   col.Field("CustomerID").HeaderText("Customer ID").Width("120").Add();
   col.Field("OrderDate").HeaderText("Order Date").Format("yMd").SortComparer("sortComparer").Width("130").Add();
   col.Field("ShipCountry").HeaderText("ShipCountry").Width("150").Add();

}).ActionBegin("actionBegin").Render()

<script type="text/javascript">
    var action;
    function actionBegin(args) {
        if (args.requestType == "sorting") {
            action = args.direction;
        }
    }

    function sortComparer(reference, comparer) {
        var sortAsc = action === "Ascending" ? true : false;
        if (sortAsc && reference === null) {
            return 1;
        }
        else if (sortAsc && comparer === null) {
            return -1;
        }
        else if (!sortAsc && reference === null) {
            return -1;
        }
        else if (!sortAsc && comparer === null) {
            return 1;
        } else {
            return reference - comparer;
        }
    }
</script>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}