Question Implicit Conversion Problem

LarryDavid

New member
Joined
Apr 28, 2013
Messages
1
Programming Experience
10+
Hello,

I have a VB.NET function I'm using to pass values, in this case simple addition to test. Here is a small class with the functions:

VB.NET:
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControlsPartial Public Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    End Sub

    Private Function GetResult(ByVal firstNumber As String, ByVal secondNumber As String, ByVal [function] As Integer) As String
        Dim a As Integer, b As Integer
        Dim result As String = Nothing

        TextBox1.Text = ""
        TextBox2.Text = ""

        If Not Integer.TryParse(firstNumber, a) Then
            TextBox1.Text = "Must be a valid 32-bit integer!"
            Return ""
        End If

        If Not Integer.TryParse(secondNumber, b) Then
            TextBox2.Text = "Must be a valid 32-bit integer!"
            Return ""
        End If

        Try
            Select Case [function]
                Case 0
                    result = firstNumber + " + " + secondNumber + " = " + Add(a, b)
                    Exit Select
                    'Case 1
                    '    result = firstNumber + " - " + secondNumber + " = " + Subtract(a, b)
                    '    Exit Select
            End Select
        Catch e As Exception
            Label1.ForeColor = System.Drawing.Color.Red
            result = "Invalid result"
        End Try
        Return result
    End Function

    Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
        Return x + y
    End Function

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        Label1.ForeColor = System.Drawing.Color.Black
        Label1.Text = GetResult(TextBox1.Text, TextBox2.Text, DropDownList1.SelectedIndex)
    End Sub

End Class

When I step through and debug this I get:
Invalid Cast Exception
Conversion from string "2 + 2 = " to type 'Double' is not valid.

When I set Option Strict On this disallows implicit conversions from 'String' to 'Double'. So I tried this for Case 0 above:
result = CStr(CDbl(firstNumber + " - " + secondNumber + " = ") + Add(a, b))
Still no go.

I have no more hair left as I've already pulled all of it out. So, any help would be greatly appreciated.

Thanks,
Larry
 
You couldn't mathematically add or subtract things like "hello" and "goodbye". This is no different. If you want to do such maths functions on the value of Textboxes, cast them to the correct types. In this example, integers.

Dim result as int = Cint(Textbox1.Text) + Cint(Textbox2.Text)
 
Last edited:

Latest posts

Back
Top