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

17 Feb 20223 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 e-grid-column tag helper.

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.

@{
    Object sortComparer = "sortComparer";
}

<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" allowSorting="true" actionBegin="actionBegin">
    <e-grid-filterSettings type="Excel"></e-grid-filterSettings>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" width="100"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" width="120"></e-grid-column>
        <e-grid-column field="OrderDate" headerText="Order Date" format="yMd" sortComparer=sortComparer width="130"></e-grid-column>
        <e-grid-column field="ShipCity" headerText="Ship City" width="120"></e-grid-column>
    </e-grid-columns>
</ejs-grid>

<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();
}