Windows Forms: Calculator using Dynamic Formula in C#

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

dynamic formula in c#Step 2: Design your calculator form as below

dynamic formula in c#

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

You need to download Mathematical.Expression, then add code to handle calculator form

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