This is a migrated thread and some comments may be shown as answers.

Sum up cells in RadGrid

14 Answers 207 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Gareth
Top achievements
Rank 1
Gareth asked on 04 Jul 2014, 10:54 AM

Hi,

I've been having problems with client side calculations for my RadGrid (EditMode="Batch", EditType="Cell").

In order to sum up cells 'a' and 'b' and display the result in cell 'c' of the selected row (and only this row) I subscribed to OnBatchEditCellValueChanged event and created javascript function (see below).

It worked fine in 2014.403.45.

When switching to the latest (2014.2.618.40) and changing to EditType="Row" (it doesn't work for "Cell" also) all of a sudden I get loads of undefined/null object errors:

Error: Unable to get value of the property 'getElementsByTagName': object is null or undefined

Callstack:
​ _getDataControl
 _openCellInEditMode
 openRowForEdit
 _open
 _openEditFromEvent
 Anonymous Function


I've spent hours researching this and still didn't manage to get this working...

I guess my question would be: could you please provide an example of a simple javascript function example that sums two cells and display the result in the third
cell of the selected row in RadGrid with EditMode="Batch", EditType="Cell".

Thank you in advance.

function BatchCellModified(sender, args) {
              var grid = $find('<%= myGrid.ClientID %>');
              var masterTable = grid.get_masterTableView();
              var rows = masterTable.get_dataItems();
              var rowArgs = args.get_row();
              var rowIndex = rowArgs.sectionRowIndex;
              var row = rows[rowIndex];
              var txtTotal = row.get_cell("Total");
        
              if (args.get_columnUniqueName() === "PD" ||
                  args.get_columnUniqueName() === "BI") {
        
                  var txtPd = (isNaN(parseFloat(row.get_cell("PD").outerText))) ? 0 : parseFloat(row.get_cell("PD").outerText);
                  var txtBi = (isNaN(parseFloat(row.get_cell("BI").outerText))) ? 0 : parseFloat(row.get_cell("BI").outerText);
        
                  var totalAmount = txtPd + txtBi;
                  txtTotal.innerHTML = totalAmount;
              }
              if (args.get_columnUniqueName() === "Total") {
                  if (txtTotal != (txtPd + txtBi)) {
                      var txtPdOutput = row.get_cell("PD");
                      txtPdOutput.innerHTML = 0;
                      var txtBiOutput = row.get_cell("BI");
                      txtBiOutput.innerHTML = 0;
                  }
              }
          };

14 Answers, 1 is accepted

Sort by
0
Gareth
Top achievements
Rank 1
answered on 04 Jul 2014, 01:52 PM
A quick update this error appears when the code is trying to set the Total cell value. So it is obviously wrong.
I rewrote this function a bit and only missing bit is updating the cell value:

I retrieve the new value from PD cell and the existing value from BI cell ok.

I just need to now update the value of the 'Total' cell.

Please let me know.

If the below could be done in a more elegant way, please advise. This code looks way to complex for what it does.

Thanks.

 
function CalculateTotalAndValidateData(sender, args) {
 
                var grid = $find('<%= myGrid.ClientID %>');
                var masterTable = grid.get_masterTableView();
                var rows = masterTable.get_dataItems();
                var rowArgs = args.get_row();
                var rowIndex = rowArgs.sectionRowIndex;
                var row = rows[rowIndex];
                var txtTotal = row.get_cell("Total");
 
                var txtPd;
                var txtBi;
                var totalAmount;
 
                if (args._columnUniqueName === "PD") {
                    txtPd = parseFloat(args._value.replace(/,/g,''));
                    txtBi = (isNaN(parseFloat(row.get_cell("BI").outerText.replace(/,/g,''))))
                        ? 0
                        : parseFloat(row.get_cell("BI").outerText.replace(/,/g,''));
 
                    totalAmount = txtPd + txtBi;
                    alert(totalAmount);
                    //txtTotal.innerHTML = totalAmount;
                }
...continue on to other cells.

}
0
Gareth
Top achievements
Rank 1
answered on 07 Jul 2014, 10:37 AM
Could someone please kindly advise on the above?

Thanks you in advance.
0
Kostadin
Telerik team
answered on 09 Jul 2014, 08:01 AM
Hi Gareth,

The appropriate way to update the cell value is to call changeCellValue of the batchEditingManager. Please check out the following code snippet.
function CalculateTotalAndValidateData(sender, args) {
 
    var grid = $find('<%= myGrid.ClientID %>');
    var masterTable = grid.get_masterTableView();
    var rows = masterTable.get_dataItems();
    var rowArgs = args.get_row();
    var rowIndex = rowArgs.sectionRowIndex;
    var row = rows[rowIndex];
    var txtTotal = row.get_cell("Total");
 
    var txtPd;
    var txtBi;
    var totalAmount;
 
    if (args._columnUniqueName === "PD") {
        txtPd = parseFloat(args._value.replace(/,/g,''));
        txtBi = (isNaN(parseFloat(row.get_cell("BI").outerText.replace(/,/g,''))))
            ? 0
            : parseFloat(row.get_cell("BI").outerText.replace(/,/g,''));
 
        totalAmount = txtPd + txtBi;
        alert(totalAmount);
        grid.get_batchEditingManager().changeCellValue(txtTotal, totalAmount);
    }
    ...continue on to other cells.
 
}


Regards,
Kostadin
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Gareth
Top achievements
Rank 1
answered on 09 Jul 2014, 08:43 AM
Hi Kostandin

Thanks for your reply.

It's seems to be working fine however due to the client side custom validation logic implemented on the grid I get 'stack overflow' error (it freezes my screen).

Is there any other way of displaying this value on the cell apart from using batchEditingManager()?

Thanks.


0
Gareth
Top achievements
Rank 1
answered on 09 Jul 2014, 10:08 AM
Kostadin,

Actually I get 'stack overflow' and frozen screen (I can see the updated value though) even with my custom validation disabled.

I have the logic implemented within a javaScript function triggered by OnBatchEditSetCellValue event.

So the manager works, except it goes into an infinite loop at some stage and that causes the stack overflow.

Is there any other way of displaying this value on the cell?

As I said - I used to be able to just use txtTotal.innerHTML = totalAmount.


Thanks.
0
Kostadin
Telerik team
answered on 11 Jul 2014, 02:46 PM
Hi Gareth,

One of my colleague has answered the support ticket which you have opened. Please check it out and if you have any additional questions I would recommend you to continue the conversation there.

Regards,
Kostadin
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Brian
Top achievements
Rank 1
answered on 29 Oct 2014, 02:40 PM
On these same lines, I have these two read-only columns that needs to display current date and logged-in user's name (from session variable) as read-only text (not as text boxes) while insert and update. I tried whatever whatever was suggested above. But I am using these and it doesn't work.

function SetLabels(sender, args) {
 
                var lupdCell = sender.get_masterTableView()._getCellByColumnUniqueNameFromTableRowElement(args.get_row(), "last_update");
                alert(lupdCell);
                // This doesn't set the value of the cell-text on inserts/updates
                sender.get_batchEditingManager().changeCellValue(lupdCell, "10/28/2014");
                alert(sender.get_batchEditingManager().getCellValue(lupdCell));
                if (args.get_columnUniqueName() == "last_update") {
                }
}


<MasterTableView CommandItemDisplay="Top" DataKeyNames="" AutoGenerateColumns="False"
                                DataSourceID="objDataSourceIN" HorizontalAlign="NotSet" EditMode="Batch">
        <BatchEditingSettings EditType="Cell" OpenEditingEvent="Click" />
 
        <Columns>
                <telerik:GridBoundColumn DataField="last_update" HeaderStyle-Width="150px" HeaderText="Date" ReadOnly="true"
                                        SortExpression="last_update" UniqueName="last_update"></telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="who" HeaderStyle-Width="200px" HeaderText="Who" ReadOnly="true"
                                        SortExpression="who" UniqueName="who"></telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="Notes" HeaderStyle-Width="410px" HeaderText="Notes" SortExpression="Notes" UniqueName="Notes">
                         <ColumnValidationSettings EnableRequiredFieldValidation="true">
                                  <RequiredFieldValidator ForeColor="Red" Text="*This field is required" Display="Dynamic">
                                  </RequiredFieldValidator>
                          </ColumnValidationSettings>
                  </telerik:GridBoundColumn>
        </Columns>
 
        <ClientSettings AllowKeyboardNavigation="true">
       <ClientEvents OnBatchEditOpening="SetLabels" OnBatchEditSetCellValue="AllSetCellValue" />
          </ClientSettings>


0
Kostadin
Telerik team
answered on 03 Nov 2014, 09:49 AM
Hi Brian,

I noticed that you are using a cell EditType which opens the batch editor only for those cells which do not have a ReadOnly property applied. In this case the columns which have this property enabled can not be edited and SetLabels function will not fire. If you need to change the last_update cell after you open the batch editor from another cell then you have to use the following approach.
function SetLabels(sender, args) {
    var lupdCell = sender.get_masterTableView()._getCellByColumnUniqueNameFromTableRowElement(args.get_row(), "last_update");
    lupdCell.innerHTML = "10/28/2014";
}

Keep in mind that this approach will change the cell value only visually but it will not replace the value in the database. If you need to replace the value in the database then you have to remove the ReadOnly property and use changeCellValue method.

Regards,
Kostadin
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Austin
Top achievements
Rank 1
answered on 15 May 2015, 05:22 PM

I'm using a RadGrid in batch edit mode as well, and I need to work with various cell values of the row that is being changed.  My grid allows new rows to be added.  This may sound crazy, but I can't figure out how to get the values of the other cells in the row.  I'm tied to the 'BatchEditCellValueChanged' method, and when I get the 'var index = args.get_row().sectionRowIndex' value it does not match up to the row numbers when used with the 'grid.get_masterTableView().get_dataItems()[index]' logic.  When doing this I get data from a different row that what is being edited.

 So what is the correct way to access other cells from an edited row on the 'BatchEditCellValueChanged' event?  I can't find an answer yet and have been looking for two days now.  Maybe I just don't know how to word the question to google?

0
Kostadin
Telerik team
answered on 19 May 2015, 01:49 PM
Hi Austin,

Are you trying to access the cells only of the edited row or you need to access some other cells as well. In case you try to access all cells of the edited row then you can hook OnBatchEditCellValueChanged and loop thought all cells of the row as demonstrated below.
function OnBatchEditCellValueChanged(sender, args) {
    var cells = args.get_row().children;
 
    for (var i = 0; i < cells.length; i++) {
        var cellValue = sender.get_batchEditingManager().getCellValue(cells[i]);
    }
}

Regards,
Kostadin
Telerik
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
0
Austin
Top achievements
Rank 1
answered on 20 May 2015, 07:05 AM
I actually only need to work with the values in the currently edited row.  As a short term solution I have simply done 'args.get_row().cells[3].innerText', for example, to work with the other cells.  This hard coded cell position, [3] in this case, is bad news for maintainability.  If anybody changes the UI layout then it would be a breaking change, not to mention if we allow the user to drag and drop the grid's column order, etc.  What I need is to be able to use the column unique name to access the cells, but don't see a way to do this.  I have drilled into the exposed cell object's methods and properties.  Oddly enough, I don't even see 'uniqueName' as a listed property when the cell is retrieved in this manner.
0
Kostadin
Telerik team
answered on 25 May 2015, 05:21 AM
Hi Austin,

You can use getCellByColumnUniqueName table view method to access any cell on the grid. For this purpose you have to pass the row object and column unique name as parameters. Please check out the following code snippet which demonstrates how to achieve that.
function OnBatchEditCellValueChanged(sender, args) {
    var columnUniqueName = "Column3";
    var rowIndex = args.get_row().id.split("__")[1];
 
    if (rowIndex && columnUniqueName) {
        var cell = args.get_tableView().getCellByColumnUniqueName(args.get_tableView().get_dataItems()[rowIndex], columnUniqueName);
    }
}

Regards,
Kostadin
Telerik
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
0
Austin
Top achievements
Rank 1
answered on 11 Aug 2015, 03:06 PM

Not sure what you are going for there, but this is what I get:

var rowIndex = args.get_row().id.split("__")[1];

//Above gives: args.get_row().id = "ctl00_DefaultContent_ctl08_rgDueFromBorrowerAtClosing_ctl00__-1"

//So the 'rowIndex' value ends up being '-1', which then makes this not work:

var cell = args.get_tableView().getCellByColumnUniqueName(args.get_tableView().get_dataItems()[​-1], 'PAC_POC');

 ​Also, will this account for the row index numbers not matching as I noted earlier?

Thanks,

0
Angel Petrov
Telerik team
answered on 14 Aug 2015, 10:57 AM
Hello Austin,

Please try modifying the client-side logic as demonstrated below and test the page again.

JavaScript:
function pageLoad() {
    // Forces the creation of the client data items
    $find('<%=RadGrid1.ClientID%>').get_masterTableView().get_dataItems();
}
 
 
function OnBatchEditCellValueChanged(sender, args) {
    var columnUniqueName = "Column3";
    var dataItem = $find(args.get_row().id);
 
    if (columnUniqueName) {
        var cell = dataItem.get_cell(columnUniqueName);
        var cellValue = cell.children[0].innerHTML.trim();
    }
}


Regards,
Angel Petrov
Telerik
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Tags
Grid
Asked by
Gareth
Top achievements
Rank 1
Answers by
Gareth
Top achievements
Rank 1
Kostadin
Telerik team
Brian
Top achievements
Rank 1
Austin
Top achievements
Rank 1
Angel Petrov
Telerik team
Share this question
or