Expression Editor for WinForms | ComponentOne
Working with Expression Editor / Create Custom Function
In This Topic
    Create Custom Function
    In This Topic

    Expression Editor provides various built-in functions to create expressions for your applications. It allows you to define custom functions using the AddFunction method of C1ExpressionEditor class. This custom function gets added to the ExpressionEditor engine and is accessible at runtime by C1ExpressionEditor for performing calculations.

    The following image shows a custom function named Factorial, added to the ExpressionEditor engine.

    Custom Function

    The following code demonstrates how a custom function is created and added to the Expression Editor panel:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            c1ExpressionEditorPanel1.ExpressionEditor = c1ExpressionEditor1;
            ExpressionItem factItem = new ExpressionItem("Factorial", "Factorial()",
            "Returns the product of an integer and all the integers below it.", ItemType.MathFuncs);
            factItem.Arguments.Add(new Argument("number", typeof(System.Double)));
            c1ExpressionEditor1.AddFunction(factItem, Factorial, 1, 1);            
        }
    
        private object Factorial(List<object> list)
        {
            List<object> items = new List<object>();
            items = items.Concat(list).ToList();
    
            int i, fact = 1, number;
            number = Convert.ToInt32(items[0]);
            for (i = 1; i <= number; i++)
            {
                fact = fact * i;
            }
    
            return fact;
        }
        private void c1ExpressionEditor1_ExpressionChanged(object sender, EventArgs e)
        {
            if (!c1ExpressionEditor1.IsValid)
            {
                txtResult.Text = "";
            }
            else
            {
                txtResult.Text = c1ExpressionEditor1.Evaluate()?.ToString();
            }
        }
    }