Calculate cell value based on values of two cells in Batch Edit Mode

Hi,
 I have the following grid:

                        <div>
                            @(Html.EJ().Grid<SlimHub.Models.QuoteSimulationPlantCost>("QuoteSimulationPlantCostsGrid")
                      .Datasource(ds => ds.Json((IEnumerable<QuoteSimulationPlantCost>)Model.QuoteSimulationPlantCosts.ToList()).UpdateURL("../PlantCostEqUpdate").InsertURL("../PlantCostEqInsert").RemoveURL("../PlantCostEqDelete").BatchURL("../PlantCostBatchUpdate").Adaptor(AdaptorType.RemoteSaveAdaptor))
                      .ShowSummary()
                        .SummaryRow(row =>
                        {
                            row.Title("Totale").SummaryColumns(col => { col.SummaryType(SummaryType.Sum).Format("{0:C}").DisplayColumn("TotalPrice").DataMember("TotalPrice").Add(); }).Add();
                        })
                      .EditSettings(edit =>
                      {
                          edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Batch);
                      })
                      .Locale("it-IT")
                      .ToolbarSettings(toolbar =>
                      {
                          toolbar.ShowToolbar().ToolbarItems(items =>
                          {
                              items.AddTool(ToolBarItems.Add);
                              items.AddTool(ToolBarItems.Edit);
                              items.AddTool(ToolBarItems.Delete);
                              items.AddTool(ToolBarItems.Update);
                              items.AddTool(ToolBarItems.Cancel);
                          }).CustomToolbarItems(
                              new List<object>() {
                                  //new Syncfusion.JavaScript.Models.CustomToolbarItem() {TemplateID = "#Details"},
                                  new Syncfusion.JavaScript.Models.CustomToolbarItem() {TemplateID = "#Details"}});
                      })
                      .AllowResizing()
                      .AllowTextWrap(true)
                      .Columns(col =>
                      {
                          col.Field("PlantCostId").HeaderText("ID").HeaderTextAlign(TextAlign.Center).IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(40).Visible(false).Add();
                          col.Field("QuoteSimId").HeaderText("ID Simulazione").HeaderTextAlign(TextAlign.Center).DefaultValue(Model.QuoteSimId).Width(100).Visible(false).Add();
                          //col.Field("EquipmentId").HeaderText("Attrezzatura").ForeignKeyField("EquipmentId").ForeignKeyValue("EquipmentDesc").DataSource((IEnumerable<object>)ViewBag.Equipments).HeaderTextAlign(TextAlign.Center).Width(80).Add();
                          col.Field("EquipmentId").HeaderText("Attrezzatura").ForeignKeyField("EquipmentId").ForeignKeyValue("EquipmentDesc").DataSource((IEnumerable<object>)ViewBag.Equipments).HeaderTextAlign(TextAlign.Center).Width(80).Add();
                          col.Field("Quantity").HeaderText("Quantità").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:n1}").EditType(EditingType.Numeric).NumericEditOptions(new Syncfusion.JavaScript.Models.EditorProperties() { DecimalPlaces = 2, MaxValue = 99999999.99, Locale = "it-IT", MinValue = 0 }).Width(30).Add();
                          col.Field("UnitPrice").HeaderText("Prezzo Unitario").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:c2}").EditType(EditingType.Numeric).NumericEditOptions(new Syncfusion.JavaScript.Models.EditorProperties() { DecimalPlaces = 2, MaxValue = 99999999.99, Locale = "it-IT", MinValue = 0 }).Width(30).Add();
                          col.Field("TotalPrice").HeaderText("Prezzo Totale").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:c2}").AllowEditing(false).Width(30).Add();
                          col.Field("Annotations").HeaderText("Note").HeaderTextAlign(TextAlign.Center).Width(80).Add();
                      })
                      .ClientSideEvents(eve =>
                      {
                          eve.ActionComplete("PlantComplete");
                          eve.Create("PlantGridCreate");
                          eve.ToolbarClick("PlantToolBarClick");
                          eve.CellEdit("CellEdit");
                          eve.CellSave("CellSave");
                          eve.QueryCellInfo("CalculateTotalPrice");
                      })
                            )
                        </div>

When I change the Quantity field or the UnitPrice field, I want the TotalePrice field to show the total price.

I use the CellSave evento for doing that.

PROBLEM 1:

when I change either the Quantity field or the UnitPrice field, I'm not able to see the new field value for the two fields (I am in batch edit mode).

Example:

    function CellSave(args){
        debugger;
        this.model.columns[2].dataSource = @Html.Raw(Json.Encode((IEnumerable<object>)ViewBag.Equipments));//EquipmentId column

        var gridObj = $("#QuoteSimulationPlantCostsGrid").data("ejGrid");
        var index = gridObj.selectedRowsIndexes;

        if (args.columnName == "Quantity") {
            var newQuantity = args.value, format;// getting the new value
            var unitPrice = gridObj.getSelectedRecords()[0].UnitPrice;
            gridObj.setCellValue(index, "TotalPrice", newQuantity*unitPrice);
        }
        if (args.columnName == "UnitPrice") {
            var newUnitPrice = args.value, format;// getting the new value
            var quantity = gridObj.getSelectedRecords()[0].Quantity;
            gridObj.setCellValue(index, "TotalPrice", quantity*newUnitPrice);
        }

        updatePlantTotals();
        updateTotals();
    }

When I access the CellSave function the second time (the first time is called after changing Quantity field), the selected line of code retreives the original quantity value and not the new edited value. How ca I solve this problem?

PROBLEM 2:

I want the TotalPrice field to be not editable. But if I don't allow editing (as highlighted), I can't change programmatically the value. How can I set the value of a disabled field?

Thanks.

18 Replies

TS Thavasianand Sankaranarayanan Syncfusion Team March 27, 2017 03:36 AM UTC

Hi Claudio, 

Thanks for contacting Syncfusion support. 

Query: Change the value of “TotalPrice” field while changing the “Quantity” or the “UnitPrice” field. 

We have analyzed your query and we suspect that you wants to change the value of column, which is not editable.  

We can achieve your requirement using the setCellText() method and cellSave event of ejGrid control. In our attached sample we have changed the “Freight” column value, which is not editable while changing the “EmployeeId” column value.  

Refer the below code example. 


@(Html.EJ().Grid<object>("FlatGrid") 
        .Datasource((IEnumerable<object>)ViewBag.datasource) 
        .ClientSideEvents(ce=> { ce.CellSave("cellSave"); }) 
        .AllowPaging()    /*Paging Enabled*/ 
        .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Batch); }) 
        .ToolbarSettings(toolbar => 
        { 
          ------------- 
        }) 
        .Columns(col => 
        { 
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add(); 
 
           col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(TextAlign.Right).Width(75).Add(); 
            col.Field("Freight").HeaderText("Freight").AllowEditing(false).TextAlign(TextAlign.Right).Width(75).Format("{0:C}").Add(); 
             
 
 
       })) 
</div> 
<script type="text/javascript"> 
    function cellSave(args) { 
   
        var gridObj = $("#FlatGrid").data("ejGrid"); 
        var rowIndex = gridObj.selectedRowsIndexes; 
 
        if (args.columnName == "EmployeeID") { // after the change the employeeid column value 
             
            var employeeID = args.value;// getting the new value in employeeid column 
 
            var cellIndex = 2; // Freight column's cellIndex 
 
            gridObj.setCellText(rowIndex, cellIndex, employeeID * 5); 
        } 
         
    } 
     
</script> 


We have prepared a sample and it can be downloadable from the below location. 


Refer the help documentation. 



Regards, 
Thavasianand S. 



CR CLAUDIO RICCARDI March 27, 2017 03:01 PM UTC

Hi,

I have applied your suggestion, but the problem persists.

When setCellText is called, the server Update method is triggered, that is Batch mode seems not to work.

from official documentation 

setCellText()

Used to update a particular cell value.

NOTE

It will work only for Local Data.This method applicable for all editMode’s except batch edit mode.


but I want to work in Batch Mode...


TS Thavasianand Sankaranarayanan Syncfusion Team March 28, 2017 05:21 PM UTC

Hi Claudio, 
 
Sorry for the inconvenience cause. 
 
We have analyzed your query and we suggest you to enable the allowEditing property while set the value for disabled column, then you can disable the allowEditing for the field. 
 
In the attached sample change the EmployeeID column value then in the cellSave event we can enable the allowEditing for the field Freight then set the value using the setCellValue() method, then disable the allowEditing for that field.  
 
Refer the below code example.  
 
 
@(Html.EJ().Grid<object>("FlatGrid") 
 
.ClientSideEvents(ce=> { ce.CellSave("cellSave"); }) 
 
------------------- 
 
<script type="text/javascript"> 
    function cellSave(args) { 
       
        var gridObj = $("#FlatGrid").data("ejGrid"); 
        var rowIndex = gridObj.selectedRowsIndexes; 
 
        if (args.columnName == "EmployeeID") { 
            debugger 
            var employeeID = args.value;// getting the new value 
            var cellIndex = 4; // Freight column's cellIndex 
            gridObj.model.columns[4]['allowEditing'] = true; // 4 denotes the freight column’s index, enable the allowEditing for the disabled column 
 
            gridObj.setCellValue(rowIndex, "Freight", employeeID * 5); 
 
            gridObj.model.columns[4]['allowEditing'] = false; // 4 denotes the freight column’s index, enable the allowEditing for the disabled column 
        } 
 
    } 
 
</script> 
 
 
We have prepared a sample and it can be downloadable from the below location. 
 
 
Regards, 
Thavasianand S. 



BF Bruno Figueiredo January 31, 2018 02:38 PM UTC

Hi,

Is there a way to do this but in Inline edit ?
I would like to have Quantity and Price columns editable and Total column not editable. And in edit mode, while i change the Quantity or Price, the Total column is displaying the calculated value, live.

In my case, the only difference from this example is the edit mode.
In Inline edit mode, the CellSave event does not get fired.

Thanks,
Bruno Figueiredo


BM Balasubramanian Masilamani Syncfusion Team February 1, 2018 12:20 PM UTC

Hi Bruno,

 

 

We have analyzed your query and we found that you are using inline editMode in grid. Since CellSave event will works only in batch edit mode so we suggest you to use EndEdit event for Inline edit mode.

 

 

Please refer the code sample:

@(Html.EJ().Grid<object>("FlatGrid") 

 

.ClientSideEvents(eve=>eve.EndEdit("endEdit")) 

------------------- 

 

<script type="text/javascript">

    function endEdit(args) {

        var gridObj = $("#FlatGrid").data("ejGrid");

        var rowIndex = gridObj.selectedRowsIndexes;

        var employeeID = args.data.EmployeeID;// getting the new value

        var cellIndex = 4; // Freight column's cellIndex

        gridObj.setCellText(rowIndex, cellIndex, employeeID * 5);

 

    }

 

</script>

 

Please find the documentation link

https://help.syncfusion.com/api/js/ejgrid#events:endedit

 

 

Please let us know if you need any further assistance.

 

Regards,

Balasubramanian Masilamani

 

 



BF Bruno Figueiredo February 1, 2018 04:17 PM UTC

Well, that works but is not live as I wanted it to be (maybe live is not the right word, but I wanted instant changes as I change the fields)

I grabbed the Thor hammer and did this to replicate this behaviour:

 $(document).on('change', "#FlatGridinlineQuantity", function () {
            calcTotal();
        });
        $(document).on('change', "#FlatGridinlineUnitPrice", function () {
            calcTotal();
        });

function calcTotal(){  get values from   $("##FlatGridinlineUnitPrice").val() and do some math }



TS Thavasianand Sankaranarayanan Syncfusion Team February 2, 2018 10:33 AM UTC

Hi Bruno, 

Thanks for contacting Syncfusion support. 

We have analyzed your query and we suspect that you want to calculate two columns then result will be displayed in third column of ejGrid. We have expression column in ejGrid control for doing calculation in columns and also it is known as a template column.  

By binding the keyup event for the Freight and EmployeeID column in the actionComplete event of ejGrid control. Then we able to do calculation while entering or typing the values in Freight and EmployeeID column’s input text box.  

For an example, we have calculated with the “Freight”, “EmployeeID” column and the result will be generated in “CalculatedColumn” 

Refer the below code example. 


@(Html.EJ().Grid<object>("FlatGrid") 
         
        .AllowPaging() 
        .ClientSideEvents(cevent => cevent.ActionComplete("complete")) 
     
         ---          
 
        .Columns(col => 
        { 
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width(75).Add(); 
            col.Field("Freight").HeaderText("Freight").Width(100).Add(); 
            col.Field("EmployeeID").HeaderText("Employee ID").Width(90).Add(); 
            col.HeaderText("Calculated Column").Template("<span id='CalcCol'>{{:EmployeeID * Freight }}</span>").Width(90).Add(); 
        })) 
</div> 
<script type="text/javascript"> 
    function complete(args) { 
        if (args.requestType == "beginedit" || args.requestType == "add") { 
            $("#" + this._id + "EmployeeID").keyup(function (event) { 
                Valuechange(); 
            }); 
            $("#" + this._id + "Freight").keyup(function (event) { 
                Valuechange(); 
            }); 
        } 
    } 
    function Valuechange(args) { 
 
       var employeeID = $("#FlatGrid" + "EmployeeID").val(); 
       var freight = $("#FlatGrid" + "Freight").val();         
       $("#CalcCol")[0].innerHTML = parseFloat(employeeID) * parseFloat(freight); 
    } 
</script> 


We have prepared a sample and it can be downloadable from the below location. 


Refer the help documentation. 



Regards, 
Thavasianand S.  



MG Marcos Gómez April 6, 2025 09:13 AM UTC

You could try updating args.rowData within CellSave to reflect the most recent changes before triggering the total calculation—this often solves the issue in batch edit mode. For non-editable fields like TotalPrice, keeping the field editable in config but preventing manual input visually (e.g., with CSS or custom editors) usually works. I've seen similar patterns used in web-based tools like https://aliciacalculadora.net/ that rely on calculated fields based on user input.



FS Farveen Sulthana Thameeztheen Basha Syncfusion Team April 8, 2025 01:19 PM UTC

Marcos Gómez,


Thanks for your valuable update. We have deprecated our EJ1 products with its Nugets and NPM Packages. So, we don't publish any new builds & packages for this product here after. Unfortunately, we will no longer be able to provide development support for this product. This means that we cannot offer bug fixes or feature implementations for EJ1 Please refer to the following link for a list of our retired products: https://help.syncfusion.com/common/essential-studio/essential-studio-retired-products

We retire products in order to maintain industry standards. It is highly recommended that you migrate to next generation JS controls. We also would like to let you know about our next generation JavaScript product - Essential JS 2in case if you are not aware of it. Essential JS 2 is fully re-written to be modular, responsive. This new-generation data grid control offers several benefits over our existing EJ1 Grid control like better performance, touch friendliness, light weight, and much more. JS2 DataGrid offers 2–3x improved performance in many scenarios.  The Essential JS 2 documentation is regularly updated and maintained.

     

We suggest you look into our following product page for more details.    

https://www.syncfusion.com/aspnet-mvc-ui-controls/grid

https://ej2.syncfusion.com/aspnetmvc/grid/gridoverview#/fluent2

https://ej2.syncfusion.com/aspnetmvc/documentation/grid/getting-started-mvc


Regards,

Farveen sulthana T




JA Jemi Anderson May 14, 2025 05:38 AM UTC

Solution to Problem 1: Use args.rowData Instead

In CellSave, args.rowData contains the current row with all latest in-memory values, including the new value just edited and any other unsaved ones in that row.

Update your CellSave like this

function CellSave(args){

    var gridObj = $("#QuoteSimulationPlantCostsGrid").data("ejGrid");

    var index = gridObj.selectedRowsIndexes[0];


    // Use args.rowData to get current values in batch mode

    var quantity = args.rowData.Quantity;

    var unitPrice = args.rowData.UnitPrice;


    var total = (quantity || 0) * (unitPrice || 0);

    gridObj.setCellValue(index, "TotalPrice", total);


    updatePlantTotals();

    updateTotals();

}



Solution to Problem 2: Mark TotalPrice as Read-Only with CSS/UI, Not Grid Setting

Instead of setting .AllowEditing(false), allow editing programmatically but prevent manual edits via a combination of CSS and event handlers.

  1. Leave .AllowEditing() default (do not disable it) for TotalPrice.

  2. Use the CellEdit event to cancel user editing:

javascript

function CellEdit(args) {

    if (args.columnName === "TotalPrice") {

        args.cancel = true; // prevents user editing

    }

}


Optionally add CSS to make it look disabled:


.e-grid .e-rowcell[aria-colindex="X"] {

    background-color: #f9f9f9;

    pointer-events: none;

}

For more details, check out the official site of Calculadora Alicia.



FS Farveen Sulthana Thameeztheen Basha Syncfusion Team May 14, 2025 10:07 AM UTC

Jemi Anderson,


Thanks for the suggestion.


Regards,
Farveen sulthana T



BC Be Clean Nj May 28, 2025 05:16 AM UTC

For Problem 1, in batch mode, unsaved changes aren't reflected in getSelectedRecords(). Instead, use args.rowData to access updated values directly during CellSave.

For Problem 2, to update a non-editable field programmatically, keep AllowEditing(true) but use readOnly: true in EditTemplate or use args.row.find('td...') to set the value manually in the DOM. This way, it's not user-editable but still updatable in code.

Read more....



FS Farveen Sulthana Thameeztheen Basha Syncfusion Team May 30, 2025 02:24 PM UTC

Be Clean Nj,


For Problem #1:


You can use the batchChanges or getBatchChanges method to retrieve all pending changes before the records are updated. This can help in managing edited records before updating/saving into the data source.
Reference: getBatchChanges - API Documentation


For Problem #2:


Based on your earlier request, the TotalPrice field was configured to be non-editable. The current implementation calculates the TotalPrice dynamically based on the values of the UnitPrice and Quantity fields.


Please confirm if you now require the TotalPrice field to be editable. If so, kindly provide more details about your exact requirement.

  • Should changes to TotalPrice affect the UnitPrice or Quantity fields?
  • Should the calculated values remain in sync?
  • Is this change applicable to specific scenarios only?


Once we have a clear understanding of your updated requirement, we’ll be happy to assist you further.



CA Calculadora Alicia July 15, 2025 05:03 PM UTC

You're facing a common challenge with Syncfusion's batch edit mode. In batch editing, the grid doesn’t immediately commit the edited value to the record object (getSelectedRecords() still returns the previous state). Instead, it holds temporary values in the internal batch changes.

✅ Solution for Problem 1:

To get the newest edited values, access them using the internal batch changes object (batchChanges.editedRecords) rather than relying on getSelectedRecords().

Here's a better way to retrieve current row values inside CellSave:

javascript
function CellSave(args) { var gridObj = $("#QuoteSimulationPlantCostsGrid").data("ejGrid"); var batchData = gridObj.batchChanges.editedRecords; var rowIndex = args.rowIndex; // Find the edited row by primary key (or use row index carefully) var editedRow = batchData.find(item => item.PlantCostId === args.row.data.PlantCostId); if (editedRow) { var quantity = editedRow.Quantity || args.row.data.Quantity; var unitPrice = editedRow.UnitPrice || args.row.data.UnitPrice; var total = (quantity * unitPrice) || 0; gridObj.setCellValue(rowIndex, "TotalPrice", total); } updatePlantTotals(); updateTotals(); }

✅ Solution for Problem 2:

If you set AllowEditing(false) on the "TotalPrice" column, the field becomes read-only and locked for updates via setCellValue.

Instead, allow editing in the grid config but disable editing visually and logically using ClientSideEvents → CellEdit:

javascript
function CellEdit(args) { if (args.columnName === "TotalPrice") { args.cancel = true; } }

This way, users can’t manually edit "TotalPrice", but you can still update it programmatically with setCellValue().


By the way, if you're also dealing with other types of numeric or educational calculations outside of construction or finance (like percentage, area, interest, or academic math), this matematicias calculadora might be helpful. It’s simple, reliable, and great for educational or quick-reference use.

Hope this helps you fix both issues cleanly! Let me know if you’d like a working JSFiddle or example code structure.



FS Farveen Sulthana Thameeztheen Basha Syncfusion Team July 16, 2025 01:10 PM UTC

Hi Calculadora Alicia,


Thanks for your suggestion.


Regards,

Farveen sulthana T





SR Sebestian Reyes October 31, 2025 11:38 AM UTC

That’s a solid breakdown of how to handle calculated fields in batch mode. I’ve also seen similar implementations where the logic uses temporary in-memory edits to keep results consistent across rows. For anyone who wants to experiment with simplified numeric computations or quick math validations, the 2025 calculator can be really handy for testing small calculation cases before finalizing grid logic.



PS Pavithra Subramaniyam Syncfusion Team November 4, 2025 04:25 AM UTC

Hi Sebestian,


Thanks for your suggestion.

Regards,
Pavithra S



AL Adriana Lima November 25, 2025 11:27 AM UTC

Use args.rowData in batch mode to get the updated values, then force-update the read-only TotalPrice with:

gridObj.setCellValue(args.rowIndex, "TotalPrice", qty * price, false);

Loader.
Up arrow icon