Well, in my opinion you're doing it wrong way.
As to the body of function...
From programming practice perspective, function should be as much universal as possible. So, it can take zero, one or more parameters, but
it shouldn't refer to the controls on the form!
Public Function Calculator(ByVal strMod As String)
Dim Num1 As Integer = TextBox1.Text
Dim Num2 As Integer = TextBox2.Text
Dim Num3 As Single = TextBox3.Text
Select Case strMod
Case Calculator("Add")
Num3 = Num1 + Num2
Case Calculator("Sub")
Num3 = Num1 - Num2
End Select
Return Num3
End Function
Your function should use 3 parameters:
- a number, which stores actual result (zero by default)
- a number, which is used for further calculation
- a sign [
+
], [-
], [*
] or [/
] - aka mathematical operator
Public Function Calculate(ByVal totalValue As Single, ByVal currentValue As Single, ByVal mathOperator As String)
Dim retVal as Single = 0
Select Case mathOperator
Case "+"
retVal = totalValue + currentValue
Case "-"
retVal = totalValue - currentValue
Case "*"
retVal = totalValue * currentValue
Case "/"
retVal = totalValue / currentValue
End Select
Return retVal
End Function
Usage:
Let's say, you have one button for addition operation [+], one for subtraction operation [-], etc, but all buttons refer to the same
Click
event (see:
How to: Connect Multiple Events to a Single Event Handler in Windows Forms[
^])
Private Sub ButtonAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonAdd.Click, ButtonSub.Click, ...
Dim tot As Single = Convert.ToSingle(Me.TextBoxResult.Text)
Dim cur As Single = Convert.ToSingle(Me.TextBoxValue.Text)
Dim moper As String = TryCast(sender, Button).Text
TextBoxResult.Text = Calculate(tot, cur, moper)
End Sub
As you can see, i used
Convert.ToSingle()[
^] method to convert string into single.
Here is MSDN example:
Windows VB.Net Calculator sample in VB.NET for Visual Studio 2008[
^]
But, finally, you need mathematical expression evaluator/parser. See:
Simple Math Parser - Home[
^]
Fast Lightweight Expression Evaluator - Home[
^]
ILCalc: Arithmetical Expressions Evaluator - Home[
^]
NCalc - Mathematical Expressions Evaluator for .NET - Home[
^]
The expression evaluator revisited (Eval function in 100% managed .NET)[
^]
A Calculation Engine for .NET[
^]