views:

375

answers:

2

I am very new to F#, and I thought I would develop a simple winform calculator to strengthen my skills with F# and .NET. I ran into two problems which probably have very simple answers, however, I could not find any assistance from my resources.

First, I want to be able to change my textbox type to integer, so that when I press my "add" button the event will add the integers and not concatenate them. For example:

btnPlus.Click.Add(fun _ -> tb1.Text <- ("2") + ("2")) gives me 22 and not 4

How do I specify integer type for a textbox or integer type for values entered into a textbox?

My next question has to do with syntax. I was just wondering how to add multiple commands to an event. That is, in the above example, let say I wanted to add the two integers, plus open another form, and run a messagebox, after clicking the button. Do I just include commas between each command, such as: btnPlus.Click.Add(fun _ -> add integers, open form, messagebox) or is there something else involved?

I apologize for the sophomoric questions. There are not enough resources on F# and winforms as there are on F# and output (i.e. print, cmd, etc..)

Thank you,

DFM

+2  A: 

I think the textbox text is always a string, but you can do e.g.

(2 + 2).ToString()

(not quite sure what you're after).

As for multiple statements inside the body of the lambda, F# is expression-based, but uses ';' or newlines for sequencing, so e.g.

(fun _ -> doFoo(); doBar())

or

(fun _ ->
    doFoo()
    doBar()
)
Brian
Thank you for the feedback. Your reply will put me in the right direction. I wanted to verify how the syntax looks for adding, subtracting, multiplying, etc... integers after a click event. Eventually, I will replace the numbers (2's) with textbox inputs, similar to a calculator.Thank you -
+1  A: 

You simply have to parse the textbox contents as an integer. You can do this via Convert.ToInt32.

open System
let string1 = "254"
let string2 = "4525"
let myNum = Convert.ToInt32(string1) + Convert.ToInt32(string2)

Edit: You could also use Int32.TryParse(string, int32) to do it.

Edit: In F#, you can just use "int", e.g. (int string1).

Tony k
Thanks for edit, Brian!
Tony k
Thanks for the second follow up. Your answer was perfect! I was able to successfully add two textbox inputs using the int method. Thanks again,DFM