# Create Custom Expression in Code

## 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

``````
{
{
InitializeComponent();
DataTable dt = new DataTable();
//comment adding of the "Price" column in order to test the custom function

for (int i = 0; i < 10; i++)
{
dt.Rows.Add(i, "product" + i, i * 1.25, i);
}

GridViewDecimalColumn col = new GridViewDecimalColumn("Calculated Column");
}
}
public class CustomExpressionContext : Telerik.Data.Expressions.ExpressionContext
{

{
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;
}
}

``````
``````

Public Sub New()
InitializeComponent()
Dim dt As DataTable = New DataTable()

For i As Integer = 0 To 10 - 1
dt.Rows.Add(i, "product" & i, i * 1.25, i)
Next

Dim col As GridViewDecimalColumn = New GridViewDecimalColumn("Calculated Column")
End Sub
End Class

Public Class CustomExpressionContext
Inherits Telerik.Data.Expressions.ExpressionContext

Public Sub New(ByVal grid As RadGridView)
Me.grid = grid
End Sub

Public Function CustomFunction(ByVal id As Integer) As Double
Dim currentRow As GridViewRowInfo = FindCurrentRowById(id)

If currentRow IsNot Nothing Then
Dim quantity As Integer = 0
Dim price As Decimal = 0

If grid.Columns.Contains("Price") AndAlso currentRow.Cells("Price").Value IsNot Nothing Then
Decimal.TryParse(currentRow.Cells("Price").Value.ToString(), price)
End If

If grid.Columns.Contains("Quantity") AndAlso currentRow.Cells("Quantity").Value IsNot Nothing Then
Integer.TryParse(currentRow.Cells("Quantity").Value.ToString(), quantity)
End If

Return CDbl((quantity * price))
End If

Return 0
End Function

Private Function FindCurrentRowById(ByVal id As Integer) As GridViewRowInfo
For Each row As GridViewRowInfo In grid.Rows

If CInt(row.Cells("Id").Value) = id Then
Return row
End If
Next

Return Nothing
End Function
End Class

``````