Refresh the data source

17 Feb 20222 minutes to read

You can add/delete the data source records through an external button. To reflect the data source changes in the grid, invoke the refresh method.

To refresh the data source:

Step 1:

Add/delete the data source record by using the following code.

    grid.dataSource.unshift(data); // add a new record.

    grid.dataSource.splice(selectedRow, 1); // delete a record.

Step 2:

Refresh the grid after the data source change by using the refresh method.

    grid.refresh(); // refresh the Grid.
<ejs-button id="add" content="Add" isPrimary="true"></ejs-button>
<ejs-button id="delete" content="Delete" isPrimary="true"></ejs-button>

<ejs-grid id="Grid" dataSource="@ViewBag.DataSource">
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID"  width="150"></e-grid-column>       
        <e-grid-column field="ShipCity" headerText="Ship City" width="150"></e-grid-column>
        <e-grid-column field="ShipName" headerText="Ship Name" width="150"></e-grid-column>
    </e-grid-columns>
</ejs-grid>

<script>
document.getElementById('add').onclick = function() {
    var grid = document.getElementById("Grid").ej2_instances[0];
    var data = { OrderID: 10247, CustomerID: "ASDFG", Freight: 40.4, OrderDate: new Date(8367642e5) };
    grid.dataSource.unshift(data); // add new record.
    grid.refresh(); // refresh the Grid.
};

document.getElementById('delete').onclick = function() {
    var grid = document.getElementById("Grid").ej2_instances[0];
    if (grid.getSelectedRowIndexes().length) {
        var selectedRow = grid.getSelectedRowIndexes()[0];
        grid.dataSource.splice(selectedRow, 1); // delete the selected record.
    } else {
        alert("No records selected for delete operation");
    }
    grid.refresh(); // refresh the Grid.
};

</script>
public IActionResult Index()
{
    ViewBag.DataSource = OrderDetails.GetAllRecords();
    return View();
}