New to Telerik UI for ASP.NET AJAX? Download free 30-day trial

Visually Update CalculatedColumns on BatchEdit Cell Value Changed

Description

RadGrid has several built-in columns for different functionalities such as interacting with Dates, Times, Numbers, for Uploading, for calculating multiple columns and many more, see Column Types

This example will show how to update Visually the GridCalculatedColumn values in real-time upon editing one of the calculated cells in Batch edit mode.

Solution


<script>

    function OnBatchEditCellValueChanged(sender, args) {

        switch (args.get_columnUniqueName()) {
            case "OrderNumbers":
            case "Price":

                var grid = sender;
                var masterTable = grid.get_masterTableView();
                var batMan = grid.get_batchEditingManager();
                // Instantiate GridDataItems Class to be able to cast TR elements to GridDataItem objects
                var dataItems = masterTable.get_dataItems();

                // Cast TR element to GridDataItem object
                var currentDataItem = args.get_row().control;

                var orderNumbersCell = currentDataItem.get_cell("OrderNumbers");
                var orderNumbers = parseInt(batMan.getCellValue(orderNumbersCell));

                var priceCell = currentDataItem.get_cell("Price");
                var price = parseInt(batMan.getCellValue(priceCell));

                var totalPrice = orderNumbers * price;

                // Since the TotalPrice is a Calculated column that cannot be edited, it has to be manually changed using JavaScript
                $(currentDataItem.get_cell("TotalPrice")).text(totalPrice);

                break;
        }
    }

</script>

<telerik:RadGrid ID="RadGrid1" runat="server" AllowPaging="True" Width="800px"
    AutoGenerateDeleteColumn="true"
    OnBatchEditCommand="RadGrid1_BatchEditCommand"
    OnNeedDataSource="RadGrid1_NeedDataSource">
    <ClientSettings>
        <ClientEvents OnBatchEditCellValueChanged="OnBatchEditCellValueChanged" />
    </ClientSettings>
    <MasterTableView DataKeyNames="OrderID" AutoGenerateColumns="False" CommandItemDisplay="Top" EditMode="Batch" PageSize="2000">
        <Columns>
            <telerik:GridBoundColumn DataField="OrderID" DataType="System.Int32"
                FilterControlAltText="Filter OrderID column" HeaderText="OrderID"
                ReadOnly="True" SortExpression="OrderID" UniqueName="OrderID">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="OrderNumbers" DataType="System.Int32"
                FilterControlAltText="Filter OrderNumbers column" HeaderText="OrderNumbers"
                SortExpression="OrderNumbers" UniqueName="OrderNumbers">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="Price" DataType="System.Int32"
                FilterControlAltText="Filter Price column" HeaderText="Price"
                SortExpression="Price" UniqueName="Price">
            </telerik:GridBoundColumn>

            <telerik:GridCalculatedColumn UniqueName="TotalPrice" HeaderText="Total Price" DataFields="OrderNumbers, Price" Expression="{0}*{1}">
            </telerik:GridCalculatedColumn>
        </Columns>
    </MasterTableView>
</telerik:RadGrid>

public DataTable SessionDataSource
{
    get
    {
        string sessionKey = "SessionDataSource";

        if (Session[sessionKey] == null || !IsPostBack)
        {

            DataTable dt = new DataTable();

            dt.Columns.Add(new DataColumn("OrderID", typeof(int)));              
            dt.Columns.Add(new DataColumn("OrderDate", typeof(DateTime)));
            dt.Columns.Add(new DataColumn("Freight", typeof(decimal)));
            dt.Columns.Add(new DataColumn("ShipName", typeof(string)));
            dt.Columns.Add(new DataColumn("ShipCountry", typeof(string)));
            dt.Columns.Add(new DataColumn("OrderNumbers", typeof(int)));
            dt.Columns.Add(new DataColumn("Price", typeof(int)));
            dt.Columns.Add(new DataColumn("TotalPrice", typeof(int)));

            dt.PrimaryKey = new DataColumn[] { dt.Columns["OrderID"] };

            for (int i = 0; i < 3; i++)
            {
                int index = i + 1;

                DataRow row = dt.NewRow();

                row["OrderID"] = index;
                row["OrderDate"] = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddHours(index);
                row["Freight"] = index * 0.1 + index * 0.01;
                row["ShipName"] = "Name " + index;
                row["ShipCountry"] = "Country " + index;
                row["OrderNumbers"] = index +index;
                row["Price"] = index * 2;

                dt.Rows.Add(row);
            }

            Session[sessionKey] = dt;
        }
        return (DataTable)Session[sessionKey];
    }
}


protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
    RadGrid1.DataSource = SessionDataSource;
}

// https://docs.telerik.com/devtools/aspnet-ajax/controls/grid/data-editing/edit-mode/batch-editing/server-side-api
protected void RadGrid1_BatchEditCommand(object sender, GridBatchEditingEventArgs e)
{
    foreach (GridBatchEditingCommand command in e.Commands)
    {
        Hashtable newValues = command.NewValues;
        Hashtable oldValues = command.OldValues;

        DataRow editedRow = newValues["OrderID"] != null ?
            SessionDataSource.Select(string.Format("OrderID = '{0}'", newValues["OrderID"].ToString())).FirstOrDefault() :
            SessionDataSource.NewRow();

        switch (command.Type)
        {
            case GridBatchEditingCommandType.Insert:
                DataRow lastOrder = SessionDataSource.Select("OrderID = MAX(OrderID)").FirstOrDefault();

                int OrderID = 1;

                if (lastOrder != null)
                {
                    OrderID = Convert.ToInt32(lastOrder["OrderID"]) + 1;
                }

                editedRow["OrderID"] = OrderID;

                foreach (string key in command.NewValues.Keys)
                {
                    editedRow[key] = newValues[key];
                }

                SessionDataSource.Rows.Add(editedRow);

                break;
            case GridBatchEditingCommandType.Update:
                foreach (string key in command.NewValues.Keys)
                {
                    if (newValues[key] != oldValues[key]) //You may want to implement stronger difference checks here, or a check for the command name (e.g., when inserting there is little point in looking up old values
                    {
                        editedRow[key] = newValues[key];
                    }
                }
                break;
            case GridBatchEditingCommandType.Delete:
                editedRow.Delete();
                break;
            default:
                break;
        }
    }
}
In this article
Not finding the help you need? Improve this article