Type Mismatch Error!

I was trying to make a calculator program, but this bug kept on bugging me:

Dim a, flag As Integer Dim b As String b = TextField1.Text TextField1.Text = "" If flag = 1 Then TextField1.Text = a + val(b) ElseIf flag = 2 Then TextField1.Text = a - val(b) ElseIf flag = 3 Then TextField1.Text = a / val(b) ElseIf flag = 4 Then TextField1.Text = a * val(b) End If

Please help out!!

TextField1.Text holds a STRING
a + val(b) gives a numeric result (an INTEGER)

you cannot put an INTEGER into a STRING - they dont match types

You will need to use either STR() or FORMAT()
Like
TextField1.Text = str(a + val(b))

Also see Using Data Types in the User Guide.

cstr() instead of str() ?

Str(a+val(b))
Str(a/val(b))
Etc.

I strongly suggest always to use cStr or CDbl for number conversion if you do not want to get stuck in localisation problems with commas and points in Numbers. For Division isn’t Double better than Integer?

May be this helps you out, I’ve commented all critical passages:

[code]Dim a, result, flag As Integer // WHERE DOES THESE VARs COME FROM? FLAG IS WITHOUT VALUE!
Dim b As String = TextField1.Text

if b <> “” then // WHAT TO DO WITH EMPTY TEXTFIELD? SHOULD CANCEL OR CALC WITH 0 INSTEAD?
select case flag
case 1
result = a + val(b)
case 2
result = a - val(b)
case 3
if val(b) <> 0 then result = a / val(b) // CAUTION: DIV BY ZERO POSSIBLE! ALWAYS CHECK YOUR DIVs!
case 4
result = a * val(b)
case else
// WHAT TO TO WHEN FLAG IS S.TH ELSE? I ASSUME RESULT AS ZERO.
result = 0
end select
end if

TextField1.Text = cstr(result)
[/code]

or more elegant as function:

TextField1.Text = DoSomething(TextField1.Text, a, flag)
function DoSomething(b as string, a as integer, flag as integer) as string

Dim result As Integer

if b <> "" then
 select case flag
 case 1
   result = a + val(b)
 case 2
   result = a - val(b)
 case 3
   if val(b) <> 0 then result = a / val(b) 
 case 4
   result = a * val(b)
 case else
   result = 0
 end select
end if

return cstr(result)

end function