Example of Formula Cell in ASP.NET MVC Data Grid Control
This sample demonstrates the Formula Cell feature in the Data Grid, which brings spreadsheet-like calculations directly into grid cells. It enables formulas to be dynamically defined and evaluated based on the values of other cells within the same row.
@* The grid's settings are in the view; the data they read (ViewData) is set in the controller action (see the controller tab). *@
@Html.UiGrid(new UiGridOptions
{
Id = "FormulaCell",
Data = ViewData["dataSource"],
Height = "400px",
EnableAutoFill = true,
Selection = UiGridSelection.Multiple,
SelectionSettings = new UiSelectionSettings { Mode = UiSelectionMode.Cell },
EditSettings = new UiEditSettings { AllowEditing = true, Mode = UiEditMode.Batch },
Columns = new List<UiGridColumn>
{
new UiGridColumn { Field = "OrderID", HeaderText = "Order ID", Type = UiColumnType.Number, Width = 100, IsPrimaryKey = true, TextAlign = UiTextAlign.Right, ValidationRules = new UiValidationRules { Required = true } },
new UiGridColumn { Field = "ProductName", HeaderText = "Product Name", Width = 200, AllowEditing = false, ValidationRules = new UiValidationRules { Required = true } },
new UiGridColumn { Field = "Category", HeaderText = "Category", Width = 130, AllowEditing = false },
new UiGridColumn { Field = "Quantity", HeaderText = "Quantity", Type = UiColumnType.Number, Width = 120, TextAlign = UiTextAlign.Right, EditType = UiEditType.NumericEdit },
new UiGridColumn { Field = "PricePerUnit", HeaderText = "Price Per Unit", Type = UiColumnType.Number, Width = 140, TextAlign = UiTextAlign.Right, EditType = UiEditType.NumericEdit, Format = "C2" },
new UiGridColumn { Field = "GrossAmount", HeaderText = "Gross Amount", Type = UiColumnType.Number, Width = 150, TextAlign = UiTextAlign.Right, Format = "C2", Formula = "Quantity * PricePerUnit" },
new UiGridColumn { Field = "TaxAmount", HeaderText = "Tax Amount", Type = UiColumnType.Number, Width = 130, TextAlign = UiTextAlign.Right, Format = "C2", AllowEditing = false, Formula = "GrossAmount * 0.07" },
new UiGridColumn { Field = "TotalAmount", HeaderText = "Total Amount", Type = UiColumnType.Number, Width = 150, TextAlign = UiTextAlign.Right, Format = "C2", Formula = "GrossAmount + TaxAmount" }
}
})
@Html.UiGrid(new UiGridOptions
{
Id = "FormulaCell",
Data = ViewData["dataSource"],
Height = "400px",
EnableAutoFill = true,
Selection = UiGridSelection.Multiple,
SelectionSettings = new UiSelectionSettings { Mode = UiSelectionMode.Cell },
EditSettings = new UiEditSettings { AllowEditing = true, Mode = UiEditMode.Batch },
Columns = new List<UiGridColumn>
{
new UiGridColumn { Field = "OrderID", HeaderText = "Order ID", Type = UiColumnType.Number, Width = 100, IsPrimaryKey = true, TextAlign = UiTextAlign.Right, ValidationRules = new UiValidationRules { Required = true } },
new UiGridColumn { Field = "ProductName", HeaderText = "Product Name", Width = 200, AllowEditing = false, ValidationRules = new UiValidationRules { Required = true } },
new UiGridColumn { Field = "Category", HeaderText = "Category", Width = 130, AllowEditing = false },
new UiGridColumn { Field = "Quantity", HeaderText = "Quantity", Type = UiColumnType.Number, Width = 120, TextAlign = UiTextAlign.Right, EditType = UiEditType.NumericEdit },
new UiGridColumn { Field = "PricePerUnit", HeaderText = "Price Per Unit", Type = UiColumnType.Number, Width = 140, TextAlign = UiTextAlign.Right, EditType = UiEditType.NumericEdit, Format = "C2" },
new UiGridColumn { Field = "GrossAmount", HeaderText = "Gross Amount", Type = UiColumnType.Number, Width = 150, TextAlign = UiTextAlign.Right, Format = "C2", Formula = "Quantity * PricePerUnit" },
new UiGridColumn { Field = "TaxAmount", HeaderText = "Tax Amount", Type = UiColumnType.Number, Width = 130, TextAlign = UiTextAlign.Right, Format = "C2", AllowEditing = false, Formula = "GrossAmount * 0.07" },
new UiGridColumn { Field = "TotalAmount", HeaderText = "Total Amount", Type = UiColumnType.Number, Width = 150, TextAlign = UiTextAlign.Right, Format = "C2", Formula = "GrossAmount + TaxAmount" }
}
})
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Lumen.UI.Mvc;
namespace YourApp.Controllers
{
public class GridController : Controller
{
// The page is Views/Grid/FormulaCell.cshtml; it draws what ViewData holds.
public ActionResult FormulaCell()
{
var data = FormulaData.GetData();
ViewData["dataSource"] = data;
return View();
}
public class FormulaData
{
public int OrderID { get; set; }
public string ProductName { get; set; }
public string Category { get; set; }
public int Quantity { get; set; }
public double PricePerUnit { get; set; }
// the three amounts are worked out by the grid: Formula on their columns
public double GrossAmount { get; set; }
public double TaxAmount { get; set; }
public double TotalAmount { get; set; }
public static List<FormulaData> GetData()
{
string[] products =
{
"Chai", "Chang", "Aniseed Syrup", "Chef Anton Gumbo Mix",
"Chef Anton Seasoning", "Grandmas Boysenberry Spread",
"Uncle Bob Organic Dried Pears", "Northwoods Cranberry Sauce",
"Mishi Kobe Niku", "Ikura", "Queso Cabrales", "Queso Manchego",
"Konbu", "Tofu", "Genen Shouyu", "Pavlova", "Alice Mutton",
"Carnarvon Tigers", "Teatime Chocolate Biscuits",
"Sir Rodneys Marmalade", "Sir Rodneys Scones",
"Gustafs Knackebrod", "Tunnbrod", "Guarana Fantastica",
"NuNuCa Nuss Nougat Creme", "Gumbear Gummibarchen",
"Schoggi Schokolade", "Rassle Sauerkraut",
"Thuringer Rostbratwurst", "Nord Ost Matjeshering",
"Gorgonzola Telino", "Mascarpone Fabioli", "Geitost",
"Sasquatch Ale", "Steeleye Stout", "Inlagd Sill",
"Gravad Lax", "Cote de Blaye", "Chartreuse Verte",
"Boston Crab Meat", "Jack New England Clam Chowder",
"Singaporean Hokkien Fried Mee", "Ipoh Coffee",
"Rogede Sild", "Spegesild", "Zaanse Koeken",
"Chocolade", "Maxilaku", "Valkoinen Suklaa",
"Manjimup Dried Apples", "Filo Mix", "Perth Pasties",
"Tourtiere", "Pate Chinois", "Gnocchi di Nonna Alice",
"Ravioli Angelo", "Escargots de Bourgogne",
"Raclette Courdavault", "Camembert Pierrot",
"Laughing Lumberjack Lager"
};
string[] categories =
{
"Beverages", "Beverages", "Condiments", "Condiments",
"Condiments", "Condiments", "Produce", "Condiments",
"Meat/Poultry", "Seafood", "Dairy Products",
"Dairy Products", "Seafood", "Produce", "Condiments",
"Confections", "Meat/Poultry", "Seafood", "Confections",
"Confections", "Confections", "Grains/Cereals",
"Grains/Cereals", "Beverages", "Confections",
"Confections", "Confections", "Produce",
"Meat/Poultry", "Seafood", "Dairy Products",
"Dairy Products", "Dairy Products", "Beverages",
"Beverages", "Seafood", "Seafood", "Beverages",
"Beverages", "Seafood", "Seafood", "Grains/Cereals",
"Beverages", "Seafood", "Seafood", "Confections",
"Confections", "Confections", "Confections",
"Produce", "Grains/Cereals", "Meat/Poultry",
"Meat/Poultry", "Meat/Poultry", "Grains/Cereals",
"Grains/Cereals", "Seafood", "Dairy Products",
"Dairy Products", "Beverages"
};
var random = new Random(12345);
var data = new List<FormulaData>();
for (int i = 1; i <= 100; i++)
{
int index = (i - 1) % products.Length;
data.Add(new FormulaData
{
OrderID = i,
ProductName = products[index],
Category = categories[index],
Quantity = random.Next(1, 11),
PricePerUnit = Math.Round(random.NextDouble() * 100 + 5, 2)
});
}
return data;
}
}
}
}
@* Install once: Install-Package Lumen.UI.Mvc (or: dotnet add package Lumen.UI.Mvc) *@
@* Views/Web.config: <add namespace="Lumen.UI.Mvc" /> *@
@* Views/Shared/_Layout.cshtml *@
<head>
@Html.UiStyles()
<link rel="stylesheet" href="~/Content/site.css" />
</head>
<body>
@RenderBody()
@Html.UiScripts()
@RenderSection("scripts", required: false)
</body>
@* Grids with a DataUrl: @Html.AntiForgeryToken() on the page and [HttpPost, ValidateJsonAntiForgeryToken] on the action. *@
In this demo, formulas are configured directly in the data source and are automatically evaluated during the initial rendering of the grid. Whenever the values of dependent cells change, the calculated fields are instantly recalculated and updated. Formula calculations are enabled for the Gross Amount, Tax Amount, and Total Amount columns by setting the allowFormula property to true. Double-click a cell to edit its value and recalculate formulas automatically.
The formulas used are:
- Gross Amount = Quantity × Price Per Unit
- Tax Amount = Gross Amount × 0.07
- Total Amount = Gross Amount + Tax Amount
When the "Quantity" or "Price Per Unit" values are modified, the Data Grid automatically recalculates the related formula-driven columns, ensuring that all computed values remain accurate and synchronized in real time.