How can i do arithmetic operations in one TextBox?

2019-06-27 01:21发布

问题:

For example i write in TextBox1

4*5 or 3-2

how can make the answer appear in the same textbox ?

I tried this but it did not work anyway

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
 textbox1.text = val(textbox1.text)
end sub

it just shows the first number

回答1:

This is a rather complex task for which there is no built-in support in the VB.NET language. The first step is to parse the text into an expression tree. The second step is to evaluate that expression tree to determine the result. The task is certainly an advanced one for beginners, but rather than doing it yourself, there are a couple other options. You could use an existing third-party library which does all of the heavy lifting for you, such as the free open-source NCalc library. Or, you could use .NET's CodeDom classes to dynamically build the expression as a .NET library and then call it to get the result.