I have some c# code that uses the Microsoft Scripting Control to evaluate some expressions:
using MSScriptControl; // references msscript.ocx
ScriptControlClass sc = new ScriptControlClass();
sc.Language = "VBScript";
sc.AllowUI = true;
try
{
Console.WriteLine(sc.Eval(txtEx.Text).ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
(txtEx is a simple text field)
Numerical expressions: "6+4", "cos(34)", "abs(-99)", "round(1.234, 2)" etc. are fine
Boolean expressions: "true or false", "1=2" are fine
But how can I evaluate a simple 'if'? I have tried "if(true, 2, 3)", "iif(true, 2, 3)", "if (true) then 2 else 3" and "if (true) then 2 else 3 endif"
Can anybody please help me to evaluate simple conditional expressions? Any help much appreciated!
RH
Try wrapping your IF-expression in a function
Add the function to the control and then use Run
(the code above is not tested, but something along that way should work)
Check out this link for some more info
http://support.microsoft.com/kb/184740
Thanks for the tips! After a bit more experimenting, based on Brummo's help, this seems to work:
txtEx contains this text:
then
sc.AddCode(txtEx.Text);
and
This isn't ideal, since I really wanted to evaluate an expression, without building, loading and evaluating a function. (I am surprised IIF doesn't work for simple one line if evaluation).
You should consider using the expression evaluation engine that is part of Windows Workflow Foundation. Both the evaluator and the designer for it can be used separately from WF.