# Windows Forms: Calculator using Dynamic Formula in C#

###### By FoxLearn 5/27/2017 9:56:48 PM   7.17K
How to create a dynamic formula using C#

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "DynamicFormula" and then click OK

Step 2: Design your calculator form as below

Step 3: Create a simple MyMath class to play demo as below

```public class MyMath
{
public double a { get; set; }
public int b { get; set; }
public double c { get; set; }
public string formula { get; set; }
public double result { get; set; }
}```

```using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Mathematical.Expressions;

namespace DynamicFormula
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnCalculate_Click(object sender, EventArgs e)
{
List<MyMath> list = dataGridView.DataSource as List<MyMath>;
if (list != null)
{
foreach(MyMath math in list)
{
//Init formula
ExpressionEval eval = new ExpressionEval(math.formula);
//Init data
eval.SetVariable("a", math.a);
eval.SetVariable("b", math.b);
eval.SetVariable("c", math.c);
//Execute formula
math.result = (double)eval.Evaluate();
}
//Update datagridview
dataGridView.DataSource = list;
dataGridView.Refresh();
}
}

private void Form1_Load(object sender, EventArgs e)
{
//Init data
List<MyMath> list = new List<MyMath>();
list.Add(new MyMath() { a = 2.1, b = 3, c = 4.5 });
list.Add(new MyMath() { a = 3.5, b = 2, c = 3.5 });
list.Add(new MyMath() { a = 4.2, b = 1, c = 1.5 });
//Set datasource to datagridview
dataGridView.DataSource = list;
}
}
}```

VIDEO TUTORIALS