Visual Basic ScriptControl won't write to variable?

1.6k views Asked by At

I'm trying to make a (very simple) graphing calculator in Visual Basic, and I used ScriptControl so that the user can input their own equation and it'll use eval() to get the result.

Public Class Form1

    Dim sc As MSScriptControl.ScriptControl = New MSScriptControl.ScriptControl

    Private Sub Form1_KeyPressed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.KeyPress, Me.Load

        sc.Language = "VBScript"
        sc.AddObject("x", 355, True)
        sc.AddCode("Sub setx(xvalo)" + vbCrLf + "x = xvalo" + vbCrLf + "End Sub")

        Me.CreateGraphics.DrawLine(Pens.Black, New Point(0, 200), New Point(5000, 200))
        Dim eq As String = InputBox("Please enter equation:")
        Dim y As Double = 0
        For i As Double = 0 To 50 Step 0.01
            sc.Run("setx", i)
            y = sc.Eval(eq)
            Me.CreateGraphics.DrawLine(Pens.Blue, New Point(i * 10, y * 10 + 200), New Point(i * 10 + 0.1, y * 10 + 0.1 + 200))
        Next

    End Sub
End Class

When I run this and type in x + 2 or even just x in the prompt box, I get an exception: NotSupportedException: Object doesn't support this property or method: 'x'

But I added x earlier... does anyone know how to fix this?

And another weird thing: It seems like whenever I try to edit the sc.AddCode() arguments, it says COMException was unhandled.

1

There are 1 answers

2
tinstaafl On

ScriptControl so that the user can input their own equation

Instead of an old legacy control not really designed for .net, you could try using the Compute method in DataTable:

            Dim dt As New DataTable()
            Try
               Dim result2 As Double = CDbl(dt.Compute(ExpressionString, ""))
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try

With the Try block invalid formulas won't stop execution

It will evaluate nested parentheses as well '(((3*(12.223+ 15)) - 7)*21)/7'.