Inline Editing in Grid Control

7 Mar 202424 minutes to read

In Normal edit mode, when you start editing the currently selected record is changed to edit state. You can change the cell values and save edited data to the data source. To enable Normal edit, set mode property of e-grid-editSettings tag helper as Normal.

<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" height="273" toolbar="@(new List<string>() { "Add", "Edit", "Delete","Update","Cancel" })">
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Normal"></e-grid-editSettings>
        <e-grid-columns>
            <e-grid-column field="OrderID" headerText="Order ID" validationRules="@(new { required=true})" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column>
            <e-grid-column field="CustomerID" headerText="Customer ID" validationRules="@(new { required=true, minLength=3})" type="string" width="120"></e-grid-column>
            <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120"></e-grid-column>
            <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>
        </e-grid-columns>
</ejs-grid>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

NOTE

Normal edit mode is default mode of editing.

Automatically update the column based on another column edited value

You can update the column value based on another column edited value by using the Cell Edit Template feature.

In the below demo, we have update the TotalCost column value based on the UnitPrice and UnitInStock column value while editing.

<ejs-grid id="Grid" dataSource=@ViewBag.DataSource height="400" toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update" })">
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Normal"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="ProductID" headerText="Product ID" textAlign="Right" isPrimaryKey="true" width="100"></e-grid-column>
        <e-grid-column field="ProductName" headerText="Product Name" width="120"></e-grid-column>
        <e-grid-column field="UnitPrice" headerText="Unit Price" editType="numericedit" edit="@(new {create = "priceCreate", read = "priceRead", destroy = "priceDestroy", write = "priceWrite"})" width="150" format="C2" textAlign="Right"></e-grid-column>
        <e-grid-column field="UnitsInStock" headerText="Units In Stock" editType="numericedit" edit="@(new {create = "stockCreate", read = "stockRead", destroy = "stockDestroy", write = "stockWrite"})" width="150" textAlign="Right"></e-grid-column>
        <e-grid-column field="TotalCost" headerText="Total Cost" width="150" allowEditing='false' format="C2" textAlign="Right"></e-grid-column>
    </e-grid-columns>
</ejs-grid>

<script>
    var priceElem;
    var priceObj;

    var stockElem;
    var stockObj;

    function priceCreate(args) {
        priceElem = document.createElement('input');
        return priceElem;
    }

    function priceWrite(args) {

        priceObj = new ej.inputs.NumericTextBox({
            value: args.rowData[args.column.field],
            change: function (args) {
                var formEle = document.getElementById("Grid").querySelector("form").ej2_instances[0];
                var totalCostFieldEle = formEle.getInputElement('TotalCost');
                totalCostFieldEle.value = priceObj.value * stockObj.value;
            }
        });
        priceObj.appendTo(priceElem);
    }

    function priceDestroy() {
        priceObj.destroy();
    }

    function priceRead(args) {
        return priceObj.value;
    }
    
    function stockCreate(args) {
        stockElem = document.createElement('input');
        return stockElem;
    }

    function stockWrite(args) {

        stockObj = new ej.inputs.NumericTextBox({
            value: args.rowData[args.column.field],
            change: function (args) {
                var formEle = document.getElementById("Grid").querySelector("form").ej2_instances[0];
                var totalCostFieldEle = formEle.getInputElement('TotalCost');
                totalCostFieldEle.value = priceObj.value * stockObj.value;
            }
        });
        stockObj.appendTo(stockElem);
    }

    function stockDestroy() {
        stockObj.destroy();
    }

    function stockRead(args) {
        return stockObj.value;
    }
   
</script>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Cancel edit based on condition

You can prevent the CRUD operations of the Grid by using condition in the actionBegin event with requestType as beginEdit for editing, add for adding and delete for deleting actions.

In the below demo, we prevent the CRUD operation based on the Role column value. If the Role Column is Employee, we are unable to edit/delete that row.

<button onclick="btnClick(event)">Grid is Addable</button>
<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" height="273" toolbar="@(new List<string>() { "Add", "Edit", "Delete","Update","Cancel" })" actionBegin="actionBegin">
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Normal"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" validationRules="@(new { required=true})" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column>
        <e-grid-column field="Role" headerText="Role" validationRules="@(new { required=true})" type="string" width="120"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120"></e-grid-column>
        <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>
    </e-grid-columns>
</ejs-grid>

<script>
    var isAddable = true;
    function actionBegin(args) {
        if (args.requestType == 'beginEdit') {
            if (args.rowData['Role'].toLowerCase() == 'employee') {
                args.cancel = true;
            }
        }
        if (args.requestType == 'delete') {
            if (args.data[0]['Role'].toLowerCase() == 'employee') {
                args.cancel = true;
            }
        }
        if (args.requestType == 'add') {
            if (!isAddable) {
                args.cancel = true;
            }
        }
    }

    function btnClick(args) {
        args.target.innerText == 'Grid is Addable' ? (args.target.innerText = 'Grid is Not Addable') : (args.target.innerText = 'Grid is Addable');
        isAddable = !isAddable;
    }
</script>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Perform CRUD action programmatically

Grid methods can be used to perform CRUD operations programmatically. The addRecord, deleteRecord, and startEdit methods are used to perform CRUD operations in the following demo.

  • To add a new record to the Grid, use the addRecord method. In this method, you can pass the data parameter to add a new record to the Grid, and the index parameter to add a record at a specific index. If you call this method with no parameters, it will create an empty row in the Grid.

  • To change the selected row to the edit state, use the startEdit method.

  • If you need to update the row data in the Grid’s datasource, you can use the updateRow method. In this method, you need to pass the index value of the row to be updated along with the updated data.

  • If you need to update the particular cell in the row, you can use the setCellValue method. In this method, you need to pass the primary key value of the data source, field name, and new value for the particular cell.

  • To remove a selected row from the Grid, use the deleteRecord method. For both edit and delete operations, you must select a row first.

NOTE

In both normal and dialog editing modes, these methods can be used.

<ejs-button id="add" content="Add" isPrimary="true"></ejs-button>
<ejs-button id="edit" content="Edit" isPrimary="true"></ejs-button>
<ejs-button id="delete" content="Delete" isPrimary="true"></ejs-button>
<ejs-button id="updaterow" content="Update Row" isPrimary="true"></ejs-button>
<ejs-button id="updatecell" content="Update Cell" isPrimary="true"></ejs-button>
<ejs-grid id="Grid" dataSource="@ViewBag.Datasource" height="270"> 
<e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" type="number" textAlign="Right" isPrimaryKey="true"  width="120"></e-grid-column>
        <e-grid-column field="EmployeeID" 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 () {
        document.getElementById('Grid').ej2_instances[0].addRecord({ "OrderID": "10001", "EmployeeID": "2", "ShipCity": "America", "ShipName": "Hanari" });
    }

    document.getElementById('edit').onclick = function () {
        document.getElementById('Grid').ej2_instances[0].startEdit();
    }

    document.getElementById('delete').onclick = function () {
        document.getElementById('Grid').ej2_instances[0].deleteRecord();
    }

    document.getElementById('updaterow').onclick = function () {
        document.getElementById('Grid').ej2_instances[0].updateRow(0, { OrderID: 10001, EmployeeID: 5, ShipCity: 'America', ShipName: 'Hanari' });
    }

    document.getElementById('updatecell').onclick = function () {
       document.getElementById('Grid').ej2_instances[0].setCellValue(document.getElementById('Grid').ej2_instances[0].currentViewData[0].OrderID, 'ShipCity', 'Value Changed');
    }
</script>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

Confirmation dialog

The delete confirm dialog can be shown when deleting a record by defining the showDeleteConfirmDialog property of e-grid-editSettings as true.

<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" height="273" toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update","Cancel"  })">
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Normal" showDeleteConfirmDialog="true"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="OrderID"  headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column>                
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="120"></e-grid-column>                
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120"></e-grid-column>          
        <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>                
    </e-grid-columns>            
</ejs-grid>
public IActionResult Index()
 {
   var orders = OrderDetails.GetAllRecords();
   ViewBag.DataSource = orders;            
   return View();
 }

NOTE

The showDeleteConfirmDialog supports all type of edit modes.

Default column values on add new row

The grid provides an option to set the default value for the columns when adding a new record in it. To set a default value for the particular column by defining the defaultValue property of e-grid-column tag helper.

<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" height="273" toolbar="@(new List<string>() { "Add", "Edit", "Delete","Update", "Cancel"})">
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Normal"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="OrderID"  headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column>                
        <e-grid-column field="CustomerID" headerText="Customer ID"  defaultValue="HANAR" type="string" width="120"></e-grid-column>                
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120"></e-grid-column>
        <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>                
    </e-grid-columns>
</ejs-grid>
public IActionResult Index()
 {
   var orders= OrderDetails.GetAllRecords();
   ViewBag.DataSource = orders;            
   return View();
 }

Adding a new row at the bottom of the Grid

By default, a new row will be added at the top of the grid. You can change it by setting newRowPosition property of [e-grid-editSettings] tag helper as Bottom.

<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" height="273" toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update" })">
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" newRowPosition="Bottom"></e-grid-editSettings>
    <e-grid-columns>
        <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column>
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="120"></e-grid-column>
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120"></e-grid-column>
        <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>
    </e-grid-columns>
</ejs-grid>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

NOTE

Add newRowPostion is supported for Normal and Batch editing modes.

Show add new row always in grid

The Syncfusion Grid simplifies the addition of new records by consistently presenting a blank, “add new row” form within the grid. To enable this feature, you can set the showAddNewRow property within the editSettings configuration to true. This allows for continuous addition of new records. You can display the add a new row at either the top or bottom of the grid content, depending on the newRowPosition property of editSettings. By default, the add new row is displayed at the top row of the grid content.

The following sample demonstrates how to add a new record continuously using showAddNewRow property.

<ejs-grid id="Grid" dataSource="@ViewBag.DataSource" height="315" toolbar="@(new List<string>() { "Add", "Edit", "Delete","Update","Cancel" })">
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" newRowPosition="Top" showAddNewRow="true"></e-grid-editSettings>
        <e-grid-columns>
            <e-grid-column field="OrderID" headerText="Order ID" validationRules="@(new { required=true})" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column>
            <e-grid-column field="CustomerID" headerText="Customer ID" validationRules="@(new { required=true, minLength=5})" type="string" width="120"></e-grid-column>
            <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120" validationRules="@(new { required=true, min=1})"></e-grid-column>
            <e-grid-column field="ShipCountry" headerText="Ship Country" width="150" editType="dropdownedit"></e-grid-column>
        </e-grid-columns>
</ejs-grid>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}

To save the newly added records, you can either hit the Enter key or click on the Update button located on the toolbar after filling in the new add form.

Limitations

  • This feature is supported only for Inline/Normal editing mode and is not compatible with other edit modes.
  • The new blank add row form will always be displayed at the top, even if you have set the new row position as the bottom for Virtual Scrolling and Infinite Scrolling enabled grid.
  • This feature is not compatible with the column virtualization feature.

Move the focus to a particular cell instead of first cell while editing a row

The recordDoubleClick event allows you to move the focus to the corresponding cell (the cell that you doubled-clicked to edit a row) instead of the first cell in edit form. With the help of this event, you can focus the double-clicked column in inline edit mode.

<div id="GridParent">
    <ejs-grid id="Grid" dataSource="@ViewBag.DataSource"  toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })" recordDoubleClick="recordDoubleClick" actionComplete="actionComplete" height="315" allowPaging="true">
     <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true"></e-grid-editSettings>
        <e-grid-columns>
            <e-grid-column field="OrderID" isPrimaryKey="true" headerText="Order ID" textAlign="Right" width="120"></e-grid-column>
            <e-grid-column field="CustomerID" headerText="Customer ID" type="string" width="120"></e-grid-column>
            <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" editType="numericedit" width="120"></e-grid-column>
            <e-grid-column field="ShipCity" headerText="Ship City" width="120"></e-grid-column>
            <e-grid-column field="ShipCountry" headerText="Ship Country" width="150"></e-grid-column>
        </e-grid-columns>
    </ejs-grid>
</div>

<script>
    var fieldName;
function recordDoubleClick(e) {
  var clickedColumnIndex = e.cell.getAttribute("aria-colindex");
  fieldName = this.columnModel[parseInt(clickedColumnIndex)].field;
}

function actionComplete(e) {
  if (e.requestType === "beginEdit") {
    // focus the column
    e.form.elements[grid.element.getAttribute("id") + fieldName].focus();
  }
}
</script>
public IActionResult Index()
{
    var Order = OrderDetails.GetAllRecords();
    ViewBag.DataSource = Order;
    return View();
}