New to Telerik UI for WinForms? Start a free 30-day trial
Create Custom Expression in Code
Updated over 6 months ago
Environment
| Product Version | Product | Author |
|---|---|---|
| 2022.2.622 | RadGridView for WinForms | Dinko Krastev |
Description
This example demonstrates how we can create custom function programmatically. In the following example, we will demonstrate how to calculate the sum of all inventory per product by multiplying the Price and Quantity columns.

Solution
C#
public partial class RadForm2 : Telerik.WinControls.UI.RadForm
{
public RadForm2()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Title", typeof(string));
//comment adding of the "Price" column in order to test the custom function
dt.Columns.Add("Price", typeof(decimal));
dt.Columns.Add("Quantity", typeof(int));
for (int i = 0; i < 10; i++)
{
dt.Rows.Add(i, "product" + i, i * 1.25, i);
}
this.radGridView1.DataSource = dt;
GridViewDecimalColumn col = new GridViewDecimalColumn("Calculated Column");
radGridView1.Columns.Add(col);
radGridView1.Columns["Calculated Column"].Expression = "CustomFunction(Id)";
Telerik.Data.Expressions.ExpressionContext.Context = new CustomExpressionContext(radGridView1);
}
}
public class CustomExpressionContext : Telerik.Data.Expressions.ExpressionContext
{
private RadGridView grid;
public CustomExpressionContext(RadGridView grid)
{
this.grid = grid;
}
public double CustomFunction(int id)
{
GridViewRowInfo currentRow = FindCurrentRowById(id);
if (currentRow != null)
{
int quantity = 0;
decimal price = 0;
if (grid.Columns.Contains("Price") && currentRow.Cells["Price"].Value != null)
{
decimal.TryParse(currentRow.Cells["Price"].Value.ToString(), out price);
}
if (grid.Columns.Contains("Quantity") && currentRow.Cells["Quantity"].Value != null)
{
int.TryParse(currentRow.Cells["Quantity"].Value.ToString(),
out quantity);
}
return (double)(quantity * price);
}
return 0;
}
private GridViewRowInfo FindCurrentRowById(int id)
{
foreach (GridViewRowInfo row in grid.Rows)
{
if ((int)row.Cells["Id"].Value == id)
{
return row;
}
}
return null;
}
}