Example 18: Race to Ten Text-Based Game

Problem: Make a simple Race to Ten text-based game. The details of the game is shown in the following screenshot:



Code:
  1. // Learn more about F# at http://fsharp.net  
  2. open System  
  3. //change the console title  
  4. System.Console.Title<-"Race to Ten"  
  5. //adds the foreground and background color  
  6. System.Console.ForegroundColor<-ConsoleColor.DarkBlue  
  7. System.Console.BackgroundColor<-ConsoleColor.Gray  
  8. //clears the screen. This is to apply the background color once the  
  9. //console application is loaded  
  10. System.Console.Clear()  
  11. //display the game title screen  
  12. printfn "\t\t\t\tRace to Ten"  
  13. printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue..."  
  14. System.Console.ReadLine()|>ignore  
  15. System.Console.Clear()  
  16. //display the game description screen  
  17. printfn "Instructions:"  
  18. printfn "In this game, each player(you vs. the computer) enters a number between 1 to 3"  
  19. printfn "The previously inputted number will be added to the present number"  
  20. printfn "The first player to enter a number that adds up to 10 wins the game"  
  21. printfn "Press Esc to quit the game"  
  22. printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue..."  
  23.   
  24. let mutable userkey=System.Console.ReadLine()  
  25. System.Console.Clear()  
  26. //declares our variables  
  27. let rndnum=new Random()  
  28. let mutable intsum=0  
  29. let mutable intusernum=0  
  30. let mutable intremain=0  
  31. //loop while sum is not equal to 10 and   
  32. //the spacebar key has been pressed  
  33. while (intsum < 10 ) do  
  34. //computer generates a number  
  35.         printfn "\n\nAI's turn..."  
  36.         let intainum=rndnum.Next(1,3)  
  37.         printfn "AI num: %d" intainum  
  38. //accumulates the number to the  
  39. //value of sum  
  40.         intsum<-intsum + intainum  
  41.         printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue...Esc to quit"  
  42.         System.Console.ReadLine()|>ignore  
  43. System.Console.Clear()  
  44. //display how many numbers more to go  
  45. //before 10  
  46. intremain<-intsum-10    
  47.         printfn "%d more to go!" intremain  
  48.  //if the sum is equal to 10   
  49.  //display "computer wins"  
  50.         if intsum>=10 then    
  51. System.Console.Clear()  
  52. //reset the value of sum so that   
  53. //the game will loop again  
  54. //remove intsum<-0 if you want the  
  55.  //game to end after one game  
  56.             printfn "Computer Wins!"   
  57.             intsum<-0  
  58.             printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue...Esc to quit"  
  59.             System.Console.ReadLine()|>ignore  
  60. System.Console.Clear()            
  61. //otherwise ask for a number           
  62. printfn "\n\nYour turn:"   
  63. intusernum<-(int)(System.Console.ReadLine())  
  64.  //if the number exceeds 3 then  
  65.  //ask for a number again  
  66.         if intusernum>3 then  
  67. printfn "Number must be between 1 to 3"  
  68. printfn "You turn:"  
  69. intusernum<-(int)(System.Console.ReadLine())  
  70.             intsum<-intsum + intusernum  
  71.             System.Console.Clear()  
  72. //accumulates the inputted number to the value of sum  
  73.         intsum<-intsum + intusernum   
  74.         intremain<-intsum-10    
  75.         printfn "%d more to go!" intremain  
  76.         if intsum>=10 then  
  77. System.Console.Clear()  
  78. printfn "You Win!"  
  79. intsum<-0  
  80.             printfn "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\tPress any key to continue...Esc to quit"  
  81.             System.Console.ReadLine()|>ignore  
  82. System.Console.Clear()  

Example#17(Array.Iter)

Problem: Make a console application that will convert the following singular nouns to plural. Use Array.Iter:

1. ally
2. army
3. baby
4. lady
5. navy

  1. // Learn more about F# at http://fsharp.net  
  2. open System  
  3. //change the console title  
  4. System.Console.Title<-"Convert to Plural"  
  5. //adds the foreground and background color  
  6. System.Console.ForegroundColor<-ConsoleColor.Blue  
  7. System.Console.BackgroundColor<-ConsoleColor.White  
  8. //clears the screen. This is to apply the background color once the  
  9. //console application is loaded  
  10. System.Console.Clear()  
  11. //assigns the singular nouns to our array variable singularnouns  
  12. let singularnouns=[|"ally";"army";"baby";"lady";"navy"|]  
  13. printfn "Singular words:"  
  14. //iterates through the values of our singularnouns array variable  
  15. singularnouns|>Array.iter(fun singularwords->printfn "%s" singularwords)  
  16. printfn "Plural words:"  
  17. //iterates through the values of our singularnouns array variable  
  18. //replace the word in each array element from "y" to "ies"  
  19. singularnouns|>Array.iter(fun pluralnouns->  
  20. let pluralwords= pluralnouns.Replace("y","ies")  
  21. printfn "%s" pluralwords)  

This will display the following output:

Visual F# 100 Examples: Example Number 16(Search a Record Value)

Problem: Make a Windows Forms Application that will allow the user to search a record value from a database file.

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Data  
  9. open System.Drawing  
  10. open System.Data.OleDb  
  11. //creates a font  
  12. let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)    
  13. //creates a connection object  
  14. let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;  
  15.   Data Source=C:\Documents and Settings\Station03\My Documents\dbEmployee.mdb")  
  16.  //creates an OleDbDataAdapter  
  17. let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblEmployee", oleconn)  
  18. //generates a dataset  
  19. let dataset11 = new DataSet()  
  20. //fills the dataset with recod values  
  21. dataadpter.Fill(dataset11,"tblEmployee")|>ignore  
  22. //creates a form  
  23. let dataform = new Form(Text="Search a Record Value",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(400, 360),StartPosition=FormStartPosition.CenterScreen)  
  24. //creates our controls  
  25. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(300, 320))   
  26. let searchbutton=new Button(Text="Search", Location=new System.Drawing.Point(220, 320))    
  27. let label1=new Label(Text="Enter the employee number:",Location=new System.Drawing.Point(0, 10),AutoSize=true)  
  28. let label2=new Label(Text="Empno:",Location=new System.Drawing.Point(0, 50),AutoSize=true)  
  29. let label3=new Label(Text="Firstname:",Location=new System.Drawing.Point(0,100),AutoSize=true)  
  30. let label4=new Label(Text="Lastname:",Location=new System.Drawing.Point(0,150),AutoSize=true)  
  31. let empnotext=new TextBox(Location=new System.Drawing.Point(200,10))  
  32. let emplabel=new Label(Location=new System.Drawing.Point(100,50),BorderStyle=BorderStyle.FixedSingle)  
  33. let fnamelabel=new Label(Location=new System.Drawing.Point(100,100),BorderStyle=BorderStyle.FixedSingle)  
  34. let lnamelabel=new Label(Location=new System.Drawing.Point(100,150),BorderStyle=BorderStyle.FixedSingle)  
  35. //creates a datagrid  
  36. let datagrid = new DataGridView(ColumnHeadersHeightSizeMode=DataGridViewColumnHeadersHeightSizeMode.AutoSize,Size=new System.Drawing.Size(300, 120),Location=new System.Drawing.Point(10, 180))  
  37. //creates a grid control colums  
  38. let chrempnocol=new DataGridViewTextBoxColumn()  
  39. let chrfnamecol=new DataGridViewTextBoxColumn()  
  40. let chrlnamecol=new DataGridViewTextBoxColumn()  
  41. //adds the columns into our datagrid  
  42. datagrid.Columns.Add(chrempnocol)|>ignore  
  43. datagrid.Columns.Add(chrfnamecol)|>ignore  
  44. datagrid.Columns.Add(chrlnamecol)|>ignore  
  45. datagrid.DataSource <- dataset11.Tables.["tblEmployee"]  
  46. //assingns the font to our form  
  47. dataform.Font<-ffont  
  48. //links our fieldname to each grid  
  49. //and change its header text  
  50. chrempnocol.DataPropertyName<-"chrempno"  
  51. chrempnocol.HeaderText<-"Employee No."  
  52. chrfnamecol.DataPropertyName<-"chrfname"  
  53. chrfnamecol.HeaderText<-"First Name"  
  54. chrlnamecol.DataPropertyName<-"chrlname"  
  55. chrlnamecol.HeaderText<-"Last Name"  
  56. //add the datagrid to our form  
  57. dataform.Controls.Add(datagrid)  
  58. //adds the controls to our form  
  59. dataform.Controls.Add(exitbutton)  
  60. dataform.Controls.Add(searchbutton)  
  61. dataform.Controls.Add(label1)  
  62. dataform.Controls.Add(label2)  
  63. dataform.Controls.Add(label3)  
  64. dataform.Controls.Add(label4)  
  65. dataform.Controls.Add(empnotext)  
  66. dataform.Controls.Add(emplabel)  
  67. dataform.Controls.Add(fnamelabel)  
  68. dataform.Controls.Add(lnamelabel)  
  69. //binds the fieldnames to our label  
  70. emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(0))  
  71. fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(1))  
  72. lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(2))  
  73. searchbutton.Click.Add(fun search->    
  74.                     //handles the row index number                 
  75.                     let mutable introws=0  
  76.                     //determines if the record has been found or not  
  77.                     let mutable blnfound=false     
  78.                     //handles the total number of records                  
  79.                     let mutable inttotrec=Convert.ToInt32(dataset11.Tables.["tblEmployee"].Rows.Count)  
  80.                     //handles the data inputted by the user  
  81.                     let strtext=Convert.ToString(empnotext.Text)  
  82.                     //while no match is found and the end of the file has not been reached  
  83.                     while((blnfound=false) && (introws<=inttotrec-1)) do  
  84.                          let strempnum=Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(0))  
  85.                          //compare the data inputted in the textbox to the employee number in our table  
  86.                          //if they are equal, display the match record  
  87.                          if strtext.ToUpper()=strempnum.ToUpper() then  
  88.                             blnfound<-true  
  89.                             emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(0))  
  90.                             fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(1))  
  91.                             lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(introws).Item(2))   
  92.                          //compare to the next record while no match is found  
  93.                          introws<-introws + 1      
  94.                     //if no match is found, display this        
  95.                     if blnfound=false then  
  96.                         MessageBox.Show("Record not found.","Search a Record Value",MessageBoxButtons.OK,MessageBoxIcon.Information)|>ignore)                         
  97. //when the exit button is clicked  
  98. exitbutton.Click.Add(fun exit->  
  99. //close the form and dataconnection  
  100.                     dataform.Close()  
  101.                     oleconn.Close())   
  102. //executes our application  
  103. Application.Run(dataform)  

Since Visual F# is very particular with the code indention, I posted below the screenshot of our code in the while loop section.



Here's what it should look like if you click the run icon:

Visual F# 100 Examples: Example 14 and 15(Pattern Matching)

Pattern matching/match with statement is similar to the switch selection statement in other programming languages. The following examples demonstrate how to use it:


Problem: Make an application that will asks a letter and displays its equivalent U. S. military phonetic alphabet.
  1. //use F# library  
  2. open System  
  3. //change the CLI title  
  4. System.Console.Title<-"Display Military Phoenitic Alphabet"  
  5. //adds color to our console application  
  6. System.Console.ForegroundColor<-ConsoleColor.Blue  
  7. //asks the user to enter a letter  
  8. printfn "Enter a letter:"  
  9. //convert the input to character and convert it to uppercase letter  
  10. //this is just for comparison purpose  
  11. let chrletter=Char.ToUpper(Convert.ToChar(System.Console.ReadLine()))  
  12. //clear the screen     
  13. System.Console.Clear()  
  14. //match the value of chrletter to the ff. values  
  15. match chrletter with  
  16. //if the value of chrletter is a or A display Alpha  
  17. 'A' ->printfn "Alpha"  
  18. //if the value of chrletter is b or B display Bravo  
  19. 'B' ->printfn "Bravo"  
  20. //if the value of chrletter is c or C display Charlie  
  21. 'C' ->printfn "Charlie"  
  22. //if the value of chrletter is d or D display Delta  
  23. 'D' ->printfn "Delta"  
  24. //if the value of chrletter is e or E display Echo  
  25. 'E'->printfn "Echo"  
  26. //if the value of chrletter is f or F display Foxtrot  
  27. 'F'->printfn "FoxTrot"  
  28. //if the value of chrletter is g or G display Golf  
  29. 'G'->printfn "Golf"  
  30. //if the value of chrletter is h or H display Hotel  
  31. 'H'->printfn "Hotel"  
  32. //if the value of chrletter is i or I display India  
  33. 'I'->printfn "India"  
  34. //if the value of chrletter is j or J display Juliet  
  35. 'J'->printfn "Juliet"  
  36. //if the value of chrletter is k or K display Kilo  
  37. 'K'->printfn "Kilo"  
  38. //if the value of chrletter is l or L display Lima  
  39. 'L'->printfn "Lima"  
  40. //if the value of chrletter m or M display Mike  
  41. 'M'->printfn "Mike"  
  42. //if the value of chrletter is n or N display November  
  43. 'N'->printfn "November"  
  44. //if the value of chrletter is o or O display Oscar  
  45. 'O'->printfn "Oscar"  
  46. //if the value of chrletter is p or P display Papa  
  47. 'P'->printfn "Papa"  
  48. //if the value of chrletter is q or Q display Quebec  
  49. 'Q'->printfn "Quebec"  
  50. //if the value of chrletter is r or R display Romeo  
  51. 'R'->printfn "Romeo"  
  52. //if the value of chrletter is s or S display Sierra  
  53. 'S'->printfn "Sierra"  
  54. //if the value of chrletter is t or T display Tango  
  55. 'T'->printfn "Tango"  
  56. //if the value of chrletter is u or U display Uniform  
  57. 'U'->printfn "Uniform"  
  58. //if the value of chrletter is v or V display Victor  
  59. 'V'->printfn "Victor"  
  60. //if the value of chrletter is w or W display Whiskey  
  61. 'W'->printfn "Whiskey"  
  62. //if the value of chrletter is x or X display X-Ray  
  63. 'X'->printfn "X-Ray"  
  64. //if the value of chrletter is y or Y display Yankee  
  65. 'Y'->printfn "Yankee"  
  66. //if the value of chrletter is z or Z display Zulu  
  67. 'Z'->printfn "Zulu"  
  68. //otherwise  
  69. | _ ->printfn "Invalid input"  
The last statement |_ is similar to the
default statement in other programming languages Switch conditional structure. It is automatically executed when no pattern match is found. Don't forget to add it at the end of every match with statement otherwise you will get an “Incomplete pattern matches on this expression” error.


Problem: Make an application that will ask the month number and display the corresponding month name and the number of days in it. Use pattern matching.

  1. //use F# library  
  2. open System  
  3. //change the CLI title  
  4. System.Console.Title<-"Display Month Name"  
  5. //adds color to our console application  
  6. System.Console.ForegroundColor<-ConsoleColor.Blue  
  7. System.Console.BackgroundColor<-ConsoleColor.White  
  8. //asks the user to enter a month number  
  9. printfn "Enter a month number(1-12):"  
  10. let intmonth=Convert.ToInt32(System.Console.ReadLine())  
  11. //clear the screen     
  12. System.Console.Clear()  
  13. //match the value of intmonth to the ff. values  
  14. match intmonth with  
  15. //if the value of intmonth is 1 display January  
  16. | 1 ->printfn "January(31 days)"  
  17. //if the value of intmonth is 2 display February  
  18. | 2 ->printfn "Febrary(28/29 days)"  
  19. //if the value of intmonth is 3 display March   
  20. | 3 ->printfn "March(31 days)"  
  21. //if the value of intmonth is 4 display April  
  22. | 4 ->printfn "April(30 days)"  
  23. //if the value of intmonth is 5 display May  
  24. | 5 ->printfn "May(31 days)"  
  25. //if the value of intmonth is 6 display June  
  26. | 6 ->printfn "June(30 days)"  
  27. //if the value of intmonth is 7 display July  
  28. | 7 ->printfn "July(31 days)"  
  29. //if the value of intmonth is 8 display August  
  30. | 8 ->printfn "August(31 days)"  
  31. //if the value of intmonth is 9 display September  
  32. | 9 ->printfn "September(30 days)"  
  33. //if the value of intmonth is 10 display October  
  34. | 10 ->printfn "October(31 days)"  
  35. //if the value of intmonth is 11 display November  
  36. | 11 ->printfn "November(30 days)"  
  37. //if the value of intmonth is 12 display December  
  38. | 12->printfn "December(31 days)"  
  39. //otherwise  
  40. | _ ->printfn "Invalid input"  

That's all for now my Visual F# friends. Ciao!

Visual F# 100 Examples: Example 12 and 13

This is the continuation of our planned 100 Visual F# examples. By the way, the bugs in examples number 7 to 11 had been fixed. My apologies, I should’nt have written those without using Visual F# compiler:)


Problem: Make a console application that will asks the user to enter the day that he was born and display his character or future based on the famous nursery rhyme written in England, “Monday’s Child”.

  1. open System  
  2. //changes the console application title  
  3. System.Console.Title<-"Tell the Future"  
  4. //adds foreground color  
  5. System.Console.ForegroundColor<-ConsoleColor.Cyan  
  6. printfn "What day were you born?"  
  7. let strday=System.Console.ReadLine()  
  8. //clears the screen  
  9. System.Console.Clear()  
  10. //converts the inputs to lowercase then compare it our  
  11. //specified values  
  12. if strday.ToLower()="monday" then  
  13.     printfn "Monday's child is fair of face"  
  14. else if strday.ToLower()="tuesday" then  
  15.     printfn "Tuesday's child is full of grace"  
  16. else if strday.ToLower()="wednesday" then  
  17.     printfn "Wednesday's child is full of woe"  
  18. else if strday.ToLower()="thursday" then  
  19.     printfn "Thurdays's child has far to go"  
  20. else if strday.ToLower()="friday" then  
  21.     printfn "Friday's child is loving and giving"  
  22. else if strday.ToLower()="saturday" then  
  23.     printfn "Saturday's child works hard for a living"  
  24. else if strday.ToLower()="sunday" then  
  25.     printfn "Sunday's child is bonny and blithe and good and gay"  
  26. else  
  27.     printfn "Invalid input"  
Problem: Develop a console application that will asks the wind speed in kilometer per hour(kph) and display its equivalent Philippine Storm Signal number.
  1. open System  
  2. //changes the console application title  
  3. System.Console.Title<-"Determine Storm Signal Number"  
  4. //adds foreground color  
  5. System.Console.ForegroundColor<-ConsoleColor.Cyan  
  6. printfn "Enter wind speed(kph):"  
  7. let intspeed=Convert.ToInt32(System.Console.ReadLine())  
  8. //clears the screen  
  9. System.Console.Clear()  
  10. //if the wind speed ranges from 30 to 60  
  11. if intspeed>=30 && intspeed<=60 then  
  12.     printfn "Storm signal number 1"  
  13. //if the wind speed ranges from 61 to 100  
  14. else if intspeed>60 && intspeed<=100 then  
  15.     printfn "Storm signal number 2"  
  16. //if the wind speed ranges from 101 to 185  
  17. else if intspeed>100 && intspeed<=185 then  
  18.     printfn "Storm signal number 3"  
  19. //if the wind speed is greater than 185  
  20. else if intspeed>185 then  
  21. printfn "Storm signal number 4"  
  22. else   
  23. printfn "Invalid input"  

Visual F# 100 Examples: Example 11

Problem: Make a simple crack the treasure chest console application game.

  1. // Learn more about F# at http://fsharp.net  
  2.   
  3. open System  
  4. //change the title to Crack the Safe  
  5. System.Console.Title<-"Crack the Safe"  
  6. //change the foreground color to green  
  7. Console.ForegroundColor<-ConsoleColor.Green  
  8. //dislay the game title screen  
  9. printfn "\t\t\t Crack the Safe"  
  10. printfn "\t\t\t Press enter to continue..."  
  11. //waits for a keypress from the user  
  12. System.Console.ReadLine()|>ignore  
  13. //Game action sequence  
  14. printfn "\t\t\t You have found a legendary treasure chest"  
  15. printfn "\t\t\t believed to contain the rarest gem on Earth"  
  16. printfn "\t\t\t Press enter to continue... "  
  17. //waits for a keypress from the user  
  18. System.Console.ReadLine()|>ignore  
  19.   
  20. printfn "\t\t\t this chest can be opened only by"  
  21. printfn "\t\t\t entering a mysterious 4-digit key code"  
  22. printfn "\t\t\t Press enter to continue..."  
  23. //waits for a keypress from the user  
  24. System.Console.ReadLine()|>ignore  
  25.   
  26. let random=new Random()  
  27. let intkeycode=Convert.ToInt32(random.Next(1000,9999))  
  28.   
  29. printfn "\t\t\tEnter the keycode:"  
  30. let intusercode= Convert.ToInt32(Console.ReadLine())  
  31. //if usercode is equal to the computer generated code then  
  32. if intusercode=intkeycode then  
  33. //display a congratulatory message  
  34.     printfn "\t\t\Congrats You have opened the treasure chest."  
  35.   
  36. //otherwise   
  37. else  
  38.     printfn "\t\t\tInvalid Code"  
  39.   
  40. printfn "\t\t\tPress enter to continue... "  
  41. System.Console.ReadLine()|>ignore  
  42. printfn "\t\t\tGame Over"  

Visual F# 100 Examples: Example 8 to 10

Problem: Make a console application that will accept five numbers and display the sum.
  1. open System  
  2. //change the title to Add Five Numbers  
  3. System.Console.Title<-"Add Five Numbers "  
  4. //change the foreground color to cyan  
  5. Console.ForegroundColor<-ConsoleColor.Cyan  
  6. printfn "\t\t\tEnter the first number:"  
  7. let intnum1=Convert.ToInt32(System.Console.ReadLine())  
  8. printfn "\t\t\tEnter the second number:"  
  9. let intnum2=Convert.ToInt32(System.Console.ReadLine())  
  10. printfn "\t\t\tEnter the third number:"  
  11. let intnum3=Convert.ToInt32(System.Console.ReadLine())  
  12. printfn "\t\t\tEnter the fourth number:"  
  13. let intnum4=Convert.ToInt32(System.Console.ReadLine())  
  14. printfn "\t\t\tEnter the fifth number:"  
  15. let intnum5=Convert.ToInt32(System.Console.ReadLine())  
  16. let  intsum=intnum1+ intnum2 + intnum3 + intnum4 + intnum5  
  17. printfn "\t\t\tThe sum is:%i" intsum  
Problem: Make a console application that will ask the power transmitted and power received then display the power loss value.
  1. open System  
  2. //change the title to Calculate Power Loss  
  3. System.Console.Title<-"Calculate Power Loss "  
  4. //change the foreground color to cyan  
  5. Console.ForegroundColor<-ConsoleColor.Cyan  
  6. printfn "\t\t\t\tPower transmitted:"  
  7. let dblpowertrans=Convert.ToDouble(System.Console.ReadLine())  
  8. printfn "\t\t\tPower recieved:"  
  9. let dblpowerrec=Convert.ToDouble(System.Console.ReadLine())  
  10. let dblpowerloss= dblpowertrans/ dblpowerrec  
  11. printfn "\t\t\t Power loss:%f " dblpowerloss  
Problem: Develop a console application that will ask the base value and height value then display the volume of a pyramid.
  1. open System  
  2. //change the title to Volume of a Pyramid  
  3. System.Console.Title<-" Volume of a Pyramid"  
  4. //change the foreground color to cyan  
  5. Console.ForegroundColor<-ConsoleColor.Cyan  
  6. printfn "\t\t\tBase value:"  
  7. let dblbase=Convert.ToDouble(System.Console.ReadLine())  
  8. printfn "\t\t\tHeight value:"  
  9. let dblheight=Convert.ToDouble(System.Console.ReadLine())  
  10. let  dblvolume=(dblbase*dblheight)/3.0  
  11. printfn "\t\t\tVolume of a pyramid:%f" dblvolume  

Visual F# 100 Examples: Example Number 7

So far I have been sharing to you guys some examples of Window Based application in Visual F#. This time, for variation sake lets make some console application:

Problem: Make a simple console application mind reader game.
  1. open System  
  2. //change the title to Simple Mind Reader Game  
  3. System.Console.Title<-"Simple Mind Reader Game"  
  4. //change the foreground color to cyan  
  5. Console.ForegroundColor<-ConsoleColor.Cyan  
  6. //dislay the game title screen  
  7. printfn "\t\t\t Mind Reader Game"  
  8. printfn "\t\t\tPress enter to continue..."  
  9. //waits for a keypress from the user  
  10. System.Console.ReadLine()|>ignore  
  11. System.Console.Clear()  
  12. //the following does the game action sequence  
  13. printfn "\t\t\t Think of a five-digit number that has five unique numbers(Eg. 12345)"  
  14. printfn "\t\t\tPress enter to continue..."  
  15. System.Console.ReadLine()|>ignore  
  16. System.Console.Clear()  
  17.   
  18. printfn "\t\t\t Reverse the numbers then subtract the smaller number from the larger number(Eg.54321- 12345)"  
  19. printfn "\t\t\tPress enter to continue..."  
  20. System.Console.ReadLine()|>ignore  
  21. System.Console.Clear()  
  22.   
  23. printfn "\t\t\t Add 10000 to the difference"  
  24. printfn "\t\t\t Press enter to continue..."  
  25. System.Console.ReadLine()|>ignore  
  26. System.Console.Clear()  
  27.   
  28. printfn "\t\t\tVisualize the sum while I try to read your mind."  
  29. printfn "\t\t\tPress enter to continue..."  
  30. System.Console.ReadLine()|>ignore  
  31. System.Console.Clear()  
  32.   
  33. printfn "\t\t\tThe sum is…"  
  34. printfn "\t\t\tPress enter to continue..."  
  35. System.Console.ReadLine()|>ignore  
  36. System.Console.Clear()  
  37.   
  38. printfn "\t\t\tThe sum is…"  
  39. printfn "\t\t\tPress enter to continue..."  
  40. System.Console.ReadLine()|>ignore  
  41. System.Console.Clear()  
  42.   
  43. printfn "\t\t\tThe sum is…"  
  44. printfn "\t\t\tPress enter to continue..."  
  45. System.Console.ReadLine()|>ignore  
  46. System.Console.Clear()  
  47.   
  48. printfn "\t\t\t51976"  

Visual F# 100 Examples: Example Number 6

Problem. Create an application that will display the surface area of a cube. The surface area of a cube can be computed by multiplying the inputted side by itself and multiplying the product by 6.
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates a new form  
  10. let cubeform=new Form(Text="Compute the Surface Area of a Cube", Size=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. //creates our controls  
  12. let n1label=new Label(Text="Enter a side value:",Location=new System.Drawing.Point(0,20),AutoSize=true)  
  13. let firsttextbox=new TextBox(Location=new System.Drawing.Point(120, 20))  
  14. let n2label=new Label(Text="Surface area of a cube:", Location=new System.Drawing.Point(0, 90),AutoSize=true)  
  15. //creates a label that will display the result of the computation  
  16. let anslabel=new Label(Location=new System.Drawing.Point(140, 90), BorderStyle=BorderStyle.FixedSingle)  
  17. //make our buttons  
  18. let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 130))  
  19. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 130))  
  20. //add the controls into the form  
  21. cubeform.Controls.Add(n1label)  
  22. cubeform.Controls.Add(firsttextbox)  
  23. cubeform.Controls.Add(n2label)  
  24. cubeform.Controls.Add(anslabel)  
  25. cubeform.Controls.Add(computebutton)  
  26. cubeform.Controls.Add(exitbutton)  
  27.   
  28. //when the compute button is clicked  
  29. computebutton.Click.Add(fun ans->  
  30. let sidevalue=Convert.ToDouble(firsttextbox.Text)  
  31. let areaofacube=6.00*(sidevalue*sidevalue)  
  32.   
  33. //display the areaofacube value in the anslabel  
  34. anslabel.Text<-Convert.ToString(areaofacube))  
  35.  //when the exit button is clicked, close the form              
  36. exitbutton.Click.Add(fun exit -> cubeform.Close())    
  37. Application.Run(cubeform)  

We'll be adding some new controls after our tenth example:)

Visual F# 100 Examples:Example Number 5

Problem: Design an application that will ask a length value, height value, and width value and display the volume of the prism.
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates our controls  
  10. let prismform=new Form(Text="Compute the Volume of a Prism", Size=new System.Drawing.Size(300, 330),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. let n1label=new Label(Text="Length value:",Location=new System.Drawing.Point(0,20),AutoSize=true)  
  12. let lenghttxtbox=new TextBox(Location=new System.Drawing.Point(80, 20))  
  13. let n2label=new Label(Text="Width value:", Location=new System.Drawing.Point(0,50),AutoSize=true)  
  14. let widthtxtbox=new TextBox(Location=new System.Drawing.Point(80,50))  
  15. let n3label=new Label(Text="Height value:", Location=new System.Drawing.Point(0, 90),AutoSize=true)  
  16. let heighttxtbox=new TextBox(Location=new System.Drawing.Point(130, 90))  
  17.   
  18. let n4label=new Label(Text="Prisms volume:", Location=new System.Drawing.Point(0, 180),AutoSize=true)  
  19. let prismlabel=new Label(Location=new System.Drawing.Point(130, 180),BorderStyle=BorderStyle.FixedSingle)  
  20. let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 250))  
  21. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 250))  
  22.   
  23. //add the controls into the form  
  24. prismform.Controls.Add(n1label)  
  25. prismform.Controls.Add(lenghttxtbox)  
  26. prismform.Controls.Add(n2label)  
  27. prismform.Controls.Add(widthtxtbox)  
  28. prismform.Controls.Add(n3label)  
  29. prismform.Controls.Add(heighttxtbox)  
  30. prismform.Controls.Add(n4label)  
  31. prismform.Controls.Add(prismlabel)  
  32. prismform.Controls.Add(computebutton)  
  33. prismform.Controls.Add(exitbutton)  
  34.   
  35. //when the compute button is clicked  
  36. computebutton.Click.Add(fun compute->  
  37. //assign the data inputted in each control to each corresponding variables  
  38. //compute the volume using the formula volume=lengthvalue*widthvalue*heightvalue  
  39. //display the result on outcome on their assigned controls  
  40. let lenghtvalue=Convert.ToDouble(lenghttxtbox.Text)  
  41. let widthvalue=Convert.ToDouble(widthtxtbox.Text)  
  42. let heightvalue=Convert.ToDouble(heighttxtbox.Text)  
  43. let prismvol=lenghtvalue*widthvalue*heightvalue  
  44. prismlabel.Text<-Convert.ToString(prismvol))  
  45.  //when the exit button is clicked, close the form              
  46. exitbutton.Click.Add(fun exit -> prismform.Close())    
  47. Application.Run(prismform)  

Visual F# 100 Examples: Example Number 4

Problem: Make an application that will display the area of an annulus (overlapping circles). The area of an annulus can be calculated by subtracting the area of a small circle from the area of a larger circle.

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates a new form  
  10. let annulform=new Form(Text="Dislay the Area of an Annulus", Size=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. //creates our controls  
  12. let n1label=new Label(Text="Area of a large circle:",Location=new System.Drawing.Point(0,20),AutoSize=true)  
  13. let firsttextbox=new TextBox(Location=new System.Drawing.Point(120, 20))  
  14. let n2label=new Label(Text="Area of a small circle:", Location=new System.Drawing.Point(0,50),AutoSize=true)  
  15. let secondtextbox=new TextBox(Location=new System.Drawing.Point(120,50))  
  16. let n3label=new Label(Text="Area of an annulus:", Location=new System.Drawing.Point(0, 90),AutoSize=true)  
  17. //creates a label that will display the result of the computation  
  18. let anslabel=new Label(Location=new System.Drawing.Point(120, 90), BorderStyle=BorderStyle.FixedSingle)  
  19. //make our buttons  
  20. let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 130))  
  21. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 130))  
  22. //add the controls into the form  
  23. annulform.Controls.Add(n1label)  
  24. annulform.Controls.Add(firsttextbox)  
  25. annulform.Controls.Add(n2label)  
  26. annulform.Controls.Add(secondtextbox)  
  27. annulform.Controls.Add(n3label)  
  28. annulform.Controls.Add(anslabel)  
  29. annulform.Controls.Add(computebutton)  
  30. annulform.Controls.Add(exitbutton)  
  31.   
  32. //when the compute button is clicked  
  33. computebutton.Click.Add(fun ans ->  
  34. let areaoflargecircle=Convert.ToDouble(firsttextbox.Text)  
  35. let areaofsmallcircle=Convert.ToDouble(secondtextbox.Text)  
  36. let areaofannulus=areaoflargecircle-areaofsmallcircle  
  37.   
  38. //display the area of annulus value in the anslabel  
  39. anslabel.Text<-Convert.ToString(areaofannulus))  
  40.  //when the exit button is clicked, close the form              
  41. exitbutton.Click.Add(fun exit -> annulform.Close())    
  42. Application.Run(annulform)  

Visual F# 100 Examples:Example Number 3

We are now on our third example of our planned 100 Visual F# windows form applications learning examples. If you noticed we are just using basic controls such as textboxes, labels, and buttons. We will add some new controls in our future examples. Meanwhile, try the following:

Problem: Create an application that will ask the name of an object or material, its voltage and current values then display its electrical resistance.

Solution:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates our controls  
  10. let resistanceform=new Form(Text="Compute Resistance", Size=new System.Drawing.Size(300, 330),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. let n1label=new Label(Text="Material:",Location=new System.Drawing.Point(0,20),AutoSize=true)  
  12. let materialtextbox=new TextBox(Location=new System.Drawing.Point(80, 20))  
  13. let n2label=new Label(Text="Current(volts):", Location=new System.Drawing.Point(0,50),AutoSize=true)  
  14. let currenttextbox=new TextBox(Location=new System.Drawing.Point(80,50))  
  15. let n3label=new Label(Text="Voltage(amperes):", Location=new System.Drawing.Point(0, 90),AutoSize=true)  
  16. let voltstextbox=new TextBox(Location=new System.Drawing.Point(130, 90))  
  17.   
  18. let n4label=new Label(Text="Material:", Location=new System.Drawing.Point(0, 180),AutoSize=true)  
  19. let materiallabel=new Label(Location=new System.Drawing.Point(130, 180),BorderStyle=BorderStyle.FixedSingle)  
  20. let n5label=new Label(Text="Resistance(ohms):", Location=new System.Drawing.Point(0, 210),AutoSize=true)  
  21. let resistancelabel=new Label(Location=new System.Drawing.Point(130, 210),BorderStyle=BorderStyle.FixedSingle)  
  22. let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 250))  
  23. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 250))  
  24.   
  25. //add the controls into the form  
  26. resistanceform.Controls.Add(n1label)  
  27. resistanceform.Controls.Add(materialtextbox)  
  28. resistanceform.Controls.Add(n2label)  
  29. resistanceform.Controls.Add(currenttextbox)  
  30. resistanceform.Controls.Add(n3label)  
  31. resistanceform.Controls.Add(voltstextbox)  
  32. resistanceform.Controls.Add(n4label)  
  33. resistanceform.Controls.Add(materiallabel)  
  34. resistanceform.Controls.Add(n5label)  
  35. resistanceform.Controls.Add(resistancelabel)  
  36. resistanceform.Controls.Add(computebutton)  
  37. resistanceform.Controls.Add(exitbutton)  
  38.   
  39. //when the compute button is clicked  
  40. computebutton.Click.Add(fun compute->  
  41. //assign the data inputted in each control to each corresponding variables  
  42. //compute the resistance using the formula resistance=voltage divided by current  
  43. //display the result on outcome on their assigned controls  
  44. let material=materialtextbox.Text  
  45. let current=Convert.ToDouble(currenttextbox.Text)  
  46. let voltage=Convert.ToDouble(voltstextbox.Text)  
  47. let resistance=voltage/current  
  48. materiallabel.Text<-material  
  49. resistancelabel.Text<-Convert.ToString(resistance))  
  50.  //when the exit button is clicked, close the form              
  51. exitbutton.Click.Add(fun exit -> resistanceform.Close())    
  52. Application.Run(resistanceform)  

Visual F# 100 Examples: Example Number 2

Last time I have shared to you our first simple example of window forms application using Visual F#, let’s now proceed to our second example:

Problem: Make a windows forms application that will ask the amount of consumption, amount of investment, government spending, amount of exports and imports and display the net emports and Gross Domestic Product (GDP).

Solution:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates our controls  
  10. let gdpform=new Form(Text="Compute GDP", Size=new System.Drawing.Size(300, 330),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. let n1label=new Label(Text="Consumption:",Location=new System.Drawing.Point(0,20),AutoSize=true)  
  12. let firsttextbox=new TextBox(Location=new System.Drawing.Point(80, 20))  
  13. let n2label=new Label(Text="Investment:", Location=new System.Drawing.Point(0,50),AutoSize=true)  
  14. let secondtextbox=new TextBox(Location=new System.Drawing.Point(80,50))  
  15. let n3label=new Label(Text="Government spending:", Location=new System.Drawing.Point(0, 90),AutoSize=true)  
  16. let thirdtextbox=new TextBox(Location=new System.Drawing.Point(130, 90))  
  17. let n4label=new Label(Text="Exports:", Location=new System.Drawing.Point(0, 120),AutoSize=true)  
  18. let fourthtextbox=new TextBox(Location=new System.Drawing.Point(130, 120))  
  19. let n5label=new Label(Text="Imports:", Location=new System.Drawing.Point(0, 150),AutoSize=true)  
  20. let fifthtextbox=new TextBox(Location=new System.Drawing.Point(130, 150))  
  21. let n6label=new Label(Text="Imports:", Location=new System.Drawing.Point(0, 180),AutoSize=true)  
  22. let netemlabel=new Label(Location=new System.Drawing.Point(130, 180),BorderStyle=BorderStyle.FixedSingle)  
  23. let n7label=new Label(Text="GDP:", Location=new System.Drawing.Point(0, 210),AutoSize=true)  
  24. let gdplabel=new Label(Location=new System.Drawing.Point(130, 210),BorderStyle=BorderStyle.FixedSingle)  
  25. let computebutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 250))  
  26. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 250))  
  27. //add the controls into the form  
  28. gdpform.Controls.Add(n1label)  
  29. gdpform.Controls.Add(firsttextbox)  
  30. gdpform.Controls.Add(n2label)  
  31. gdpform.Controls.Add(secondtextbox)  
  32. gdpform.Controls.Add(n3label)  
  33. gdpform.Controls.Add(thirdtextbox)  
  34. gdpform.Controls.Add(n4label)  
  35. gdpform.Controls.Add(fourthtextbox)  
  36. gdpform.Controls.Add(n5label)  
  37. gdpform.Controls.Add(fifthtextbox)  
  38. gdpform.Controls.Add(n6label)  
  39. gdpform.Controls.Add(netemlabel)  
  40. gdpform.Controls.Add(n7label)  
  41. gdpform.Controls.Add(gdplabel)  
  42. gdpform.Controls.Add(computebutton)  
  43. gdpform.Controls.Add(exitbutton)  
  44. //when the compute button is clicked  
  45. computebutton.Click.Add(fun compute->  
  46. //assigned the numbers inputted to each textbox to their corresponding variable  
  47. //compute the net emport using the formula net emport=export-import  
  48. //compute the gdp using the formula gdp=consumption+investment+govspending+netemport  
  49. let consumption=Convert.ToDouble(firsttextbox.Text)  
  50. let investment=Convert.ToDouble(secondtextbox.Text)  
  51. let govspending=Convert.ToDouble(thirdtextbox.Text)  
  52. let export=Convert.ToDouble(fourthtextbox.Text)  
  53. let import=Convert.ToDouble(fifthtextbox.Text)  
  54. let netemport=export-import  
  55. let gdp=(consumption+investment+govspending+netemport)  
  56. netemlabel.Text<-Convert.ToString(netemport)  
  57.                  gdplabel.Text<-Convert.ToString(gdp))  
  58.  //when the exit button is clicked, close the form              
  59. exitbutton.Click.Add(fun exit -> gdpform.Close())    
  60. Application.Run(gdpform)  

Visual F# 100 Examples: Example Number 1

Starting today, I will be sharing to you guys some learning examples that will aid you in learning windows forms application programming in Visual F#. Our target is to be able to share at least 100 examples. Let’s start with example number 1:

Problem: Make a windows form application that will ask the user’s mental age and chronological age and display his intelligence quotient (IQ).

Solution:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates a new form  
  10. let iqform=new Form(Text="Compute IQ", Size=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. //creates a label  
  12. let n1label=new Label(Text="Mental age:",Top=20,Left=5,AutoSize=true)  
  13. let firsttextbox=new TextBox(Location=new System.Drawing.Point(80, 20))  
  14. //creates another label and change its text to “Second number:”  
  15. let n2label=new Label(Text="Chronological age:", Location=new System.Drawing.Point(0,50),AutoSize=true)  
  16. let secondtextbox=new TextBox(Location=new System.Drawing.Point(100,50))  
  17. //creates another label and change its text to sum  
  18. let n3label=new Label(Text="IQ:", Location=new System.Drawing.Point(0, 90),AutoSize=true)  
  19. //creates a label that will display the result of the computation  
  20. let anslabel=new Label(Location=new System.Drawing.Point(80, 90), BorderStyle=BorderStyle.FixedSingle)  
  21. //make our buttons  
  22. let addbutton=new Button(Text="Compute", Location=new System.Drawing.Point(100, 130))  
  23. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 130))  
  24. //add the controls into the form  
  25. iqform.Controls.Add(n1label)  
  26. iqform.Controls.Add(firsttextbox)  
  27. iqform.Controls.Add(n2label)  
  28. iqform.Controls.Add(secondtextbox)  
  29. iqform.Controls.Add(n3label)  
  30. iqform.Controls.Add(anslabel)  
  31. iqform.Controls.Add(addbutton)  
  32. iqform.Controls.Add(exitbutton)  
  33.   
  34. //when the compute button is clicked  
  35. addbutton.Click.Add(fun addfunction ->  
  36. let manum=Convert.ToDouble(firsttextbox.Text)  
  37. let canum=Convert.ToDouble(secondtextbox.Text)  
  38. let iq=Convert.ToDouble((manum/canum)*100.00)  
  39.   
  40. //display the iq value in the anslabel  
  41. anslabel.Text<-Convert.ToString(iq))  
  42.  //when the exit button is clicked, close the form              
  43. exitbutton.Click.Add(fun exit -> iqform.Close())    
  44. Application.Run(iqform)  

Simplest input validation using Char.IsNumber and Char.IsLetter

The following example demonstrates how to validate a user input by using the Char.IsNumber and Char.IsLetter character manipulation functions:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. //creates a font  
  10. let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)    
  11. let validateform = new Form(Text="Validate Inputs",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)  
  12. //creates our controls  
  13. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 170))    
  14. let okbutton=new Button(Text="Ok", Location=new System.Drawing.Point(100, 170))   
  15. let label1=new Label(Text="Enter a name:",Location=new System.Drawing.Point(0, 10),AutoSize=true)  
  16. let nametxtbox=new TextBox(Location=new System.Drawing.Point(120,10),BorderStyle=BorderStyle.FixedSingle)  
  17. validateform.Font<-ffont  
  18. //adds the controls to our form  
  19. validateform.Controls.Add(exitbutton)  
  20. validateform.Controls.Add(okbutton)  
  21. validateform.Controls.Add(label1)  
  22. validateform.Controls.Add(nametxtbox)  
  23. //when the oK button is clicked  
  24. okbutton.Click.Add(fun ok->  
  25. //if the input begins with a letter then  
  26. if (Char.IsLetter(Convert.ToChar(nametxtbox.Text.Chars(0)))) then  
  27. //prompt that its a valid name  
  28. MessageBox.Show("The name you entered is valid ""Validate Inputs",MessageBoxButtons.OK, MessageBoxIcon.Information)|>ignore  
  29. //if the input begins with a number then                           
  30. if (Char.IsNumber(Convert.ToChar(nametxtbox.Text.Chars(0)))) then  
  31. //prompt that its an invalid name  
  32. MessageBox.Show("You must enter a valid name""Validate Inputs",MessageBoxButtons.OK, MessageBoxIcon.Information)|>ignore)  
  33. //when the exit button is clicked  
  34. exitbutton.Click.Add(fun exit->validateform.Close())  
  35. //executes our application  
  36. Application.Run(validateform)  
Click the run icon when done entering these codes in Visual F# code editor window. Try entering any number in the name text box and clicking the ok button. You should see an output similar to the following:

Paint Application in Visual F#

The following example demonstrates how to make a simple Paint-like application in Visual F#:

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. open System.Drawing.Drawing2D  
  10. let drawingform = new Form(Text="Draw Objects",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  11. //creates our control  
  12. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  13. let erasebutton=new Button(Text="Erase", Location=new System.Drawing.Point(120, 200))  
  14. let colorbutton=new Button(Text="Brush Color", Location=new System.Drawing.Point(40, 200))  
  15. drawingform.Controls.Add(exitbutton)  
  16. drawingform.Controls.Add(erasebutton)  
  17. drawingform.Controls.Add(colorbutton)  
  18. //creates a color dialog box  
  19. let colordlg=new ColorDialog()  
  20. //creates a colorblend object  
  21. let mutable color=new ColorBlend()  
  22.   
  23. let gr=drawingform.CreateGraphics()  
  24. gr.SmoothingMode<-SmoothingMode.HighQuality  
  25. //when the form is loaded, change its color to white  
  26. drawingform.Load.Add(fun background->  
  27. //set the default brush color to indigo  
  28. color.Colors<-[|Color.Indigo|]  
  29.                         drawingform.BackColor<-Color.White)  
  30.   
  31. drawingform.MouseMove.Add(fun trail->  
  32. //when the mouse button is moved and the left button is clicked  
  33.   
  34. if (trail.Button=System.Windows.Forms.MouseButtons.Left)then  
  35. //draw the object assign the color seleted from the color dialog as a brush color  
  36. gr.FillRectangle(new SolidBrush(color.Colors.[0]),new Rectangle(trail.X,trail.Y,5,5)))   
  37. //when the erase button is clicked  
  38. //erase the object drawn in the form  
  39. erasebutton.Click.Add(fun erase->gr.Clear(Color.White))   
  40. //when the exit button is clicked  
  41. //quit the form                                                                                                                
  42. exitbutton.Click.Add(fun quit->drawingform.Close())  
  43. //when the brush color button is selected                                                            
  44. colorbutton.Click.Add(fun colors->  
  45. //display the Color Dialog box  
  46. if colordlg.ShowDialog()=DialogResult.OK then  
  47. //store the value selected by the user in our colorblend object  
  48. color.Colors<-[|colordlg.Color|])  
  49. //executes our application  
  50. Application.Run(drawingform)  
Click the run icon once you are done entering these codes in the code editor window. You should see the following outputs:

Mouse Trails using Basic shapes

Obsessed with mouse trails? Try the following sample applications:
1. Line Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.DrawLine(Pens.Peru,trail.X,trail.Y,trail.X+1,trail.Y+1))                                                                                                                  
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

2. Circle Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.DrawEllipse(Pens.IndianRed,new Rectangle(trail.X,trail.Y,10,10)))                                                                                                                      
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

3. Rectangle Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.DrawRectangle(Pens.Fuchsia,new Rectangle(trail.X,trail.Y,5,5)))                                                                                                                      
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

4. Arc Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.DrawArc(Pens.Violet,new Rectangle(trail.X,trail.Y,5,5),180.0f,-180.0f))                                                                                                                 
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

5. Filled-Arc/FillPie Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.FillPie(Brushes.MidnightBlue,new Rectangle(trail.X,trail.Y,10,10),180.0f,180.0f))                                                                                                                 
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

6. Filled Circle Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.FillEllipse(Brushes.Tomato,new Rectangle(trail.X,trail.Y,10,10)))                                                                                                                 
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

7. Filled Rectangle Mouse Trail
Code:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let trailform = new Form(Text="Display Mouse Trail",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let gr=trailform.CreateGraphics()  
  13. trailform.Controls.Add(exitbutton)  
  14. trailform.MouseMove.Add(fun trail->gr.FillRectangle(Brushes.Indigo,new Rectangle(trail.X,trail.Y,20,20)))                                                                                                                 
  15. exitbutton.Click.Add(fun quit->trailform.Close())                                                            
  16. //executes our application  
  17. Application.Run(trailform)  
Output:

Creating a Customized Mouse Pointer

Aside from using pre-defined mouse pointers such as Cursors.Arrow and Cursors.Cross, you can also use customized mouse pointers in Visual F#. Follow these steps for a simple example:

1. Download a cursor creator software such as Axialis CursorWorkShop or Icon Craft.

2. Create a .cur file and name it “pointer.cur”.

3. Start Visual F#>Create a new Project.

4. Enter the following codes:

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. let mouseform = new Form(Text="Cutom Mouse Pointer",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  10. //creates our control  
  11. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  12. let customcur=new System.Windows.Forms.Cursor("pointer.cur")  
  13. mouseform.MouseHover.Add(fun cutom->mouseform.Cursor<-customcur)   
  14. mouseform.Controls.Add(exitbutton)                                                                                                  
  15. exitbutton.Click.Add(fun quit->mouseform.Close())                                                            
  16. //executes our application  
  17. Application.Run(mouseform)  

5. Click the Open Folder>bin>debug> then copy and paste pointer.cur.

6. Run your application

Printing an Image Data

To print an image or text, use a PrintDocument control. To following example shows how to print an image data, using a PrintDocument control.

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System.Collections.Generic  
  5. open System  
  6. open System.Windows.Forms  
  7. open System.ComponentModel  
  8. open System.Drawing  
  9. open System.Drawing.Printing  
  10.   
  11. open System.Drawing.Imaging  
  12. let imageform = new Form(Text="Print Form",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  13. //creates our control  
  14. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 200))  
  15. let loadbutton=new Button(Text="Load", Location=new System.Drawing.Point(120, 200))  
  16. let prnbutton=new Button(Text="Print", Location=new System.Drawing.Point(40, 200))  
  17. let pic=new PictureBox(SizeMode=PictureBoxSizeMode.StretchImage,Location=new System.Drawing.Point(20, 20),BorderStyle=BorderStyle.FixedSingle,Size=new System.Drawing.Size(100, 100))  
  18. let label=new Label(AutoSize=true,Location=new System.Drawing.Point(0, 120))  
  19. let dlg=new OpenFileDialog()  
  20. let gr=imageform.CreateGraphics()  
  21. let prn=new System.Drawing.Printing.PrintDocument()  
  22. imageform .Controls.Add(pic)  
  23. imageform.Controls.Add(loadbutton)  
  24. imageform.Controls.Add(label)  
  25. imageform.Controls.Add(prnbutton)  
  26. imageform.Controls.Add(exitbutton)  
  27. //sends the data to the printer  
  28. prnbutton.Click.Add(fun startprint->prn.Print())  
  29.   
  30. loadbutton.Click.Add(fun load->  
  31. //filter dialog result  
  32. dlg.Filter <- "JPEG Images (*.jpg,*.jpeg)|*.jpg;*.jpeg|Gif Images (*.gif)|*.gif"  
  33. //adds title to your dialog box  
  34.                    dlg.Title<-"Select an Image File"  
  35.                    if dlg.ShowDialog()=DialogResult.OK then  
  36. //creates a bitmap object  
  37. //assigns the image selected by the user as its value  
  38.                       let bmp=new System.Drawing.Bitmap(dlg.FileName)  
  39.                       bmp.RotateFlip(RotateFlipType.RotateNoneFlipNone)  
  40. //assigns the loaded image as a picturebox value  
  41.                       pic.Image<-bmp  
  42. //displays the image url in our label  
  43.                       label.Text<-"\t\tFilename:" + Convert.ToString(Convert.ToChar(32))+ (dlg.FileName))   
  44. //specifies the data to be printed  
  45. //in this case our image                        
  46. prn.PrintPage.Add(fun printdata->gr.DrawImage(pic.Image,10,10))  
  47. //close the form                                                                                                          
  48. exitbutton.Click.Add(fun quit->imageform.Close())                                           
  49. [<stathread>]                      
  50. //executes our application  
  51. Application.Run(imageform)  
  52. </stathread>  

Drawing Triangles and Circles

To draw a triangle, use the DrawLine or DrawPolygon method. Here’s an example that uses DrawPolygon method:
  1. // Learn more about F# at http://fsharp.net  
  2. // Learn more about F# at http://fsharp.net  
  3. //specifies the memory location of the class files  
  4. //that will be needed in our application  
  5. open System.Collections.Generic  
  6. open System  
  7. open System.Windows.Forms  
  8. open System.ComponentModel  
  9. open System.Drawing  
  10. let graphicform = new Form(Text="Draw Triangle",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  11. //creates our control  
  12. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 200))  
  13. graphicform.Paint.Add(fun draw->  
  14. let array=[|new Point(0,150);new Point(150,10);new Point(300,150)|]  
  15. let pen=new Pen(Color.Blue,Width=12.0f)  
  16. draw.Graphics.DrawPolygon(pen,array))  
  17. graphicform.Controls.Add(exitbutton)  
  18. //executes our application  
  19. Application.Run(graphicform)  
To draw a filled triangle, use the FillPolygon method:
  1. // Learn more about F# at http://fsharp.net  
  2. // Learn more about F# at http://fsharp.net  
  3. //specifies the memory location of the class files  
  4. //that will be needed in our application  
  5. open System.Collections.Generic  
  6. open System  
  7. open System.Windows.Forms  
  8. open System.ComponentModel  
  9. open System.Drawing  
  10. let graphicform = new Form(Text="Draw Triangle",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  11. //creates our control  
  12. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 200))  
  13. graphicform.Paint.Add(fun draw->  
  14. let array=[|new Point(0,150);new Point(150,10);new Point(300,150)|]  
  15. let brush=new SolidBrush(Color.Blue)  
  16. draw.Graphics.FillPolygon(brush,array))  
  17. graphicform.Controls.Add(exitbutton)  
  18. //executes our application  
  19. Application.Run(graphicform)  
To draw a circle, use the DrawEllipse method:
  1. // Learn more about F# at http://fsharp.net  
  2. // Learn more about F# at http://fsharp.net  
  3. //specifies the memory location of the class files  
  4. //that will be needed in our application  
  5. open System.Collections.Generic  
  6. open System  
  7. open System.Windows.Forms  
  8. open System.ComponentModel  
  9. open System.Drawing  
  10. let graphicform = new Form(Text="Draw Circle",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  11. //creates our control  
  12. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 200))  
  13. graphicform.Paint.Add(fun draw->  
  14.   
  15. let pen=new Pen(Color.Blue,Width=12.0f)  
  16. draw.Graphics.DrawEllipse(pen,0.0f,0.0f,100.0f,100.0f))  
  17.   
  18. graphicform.Controls.Add(exitbutton)  
  19. //executes our application  
  20. Application.Run(graphicform)  
To draw a solid circle, use the FillEllipse method:
  1. // Learn more about F# at http://fsharp.net  
  2. // Learn more about F# at http://fsharp.net  
  3. //specifies the memory location of the class files  
  4. //that will be needed in our application  
  5. open System.Collections.Generic  
  6. open System  
  7. open System.Windows.Forms  
  8. open System.ComponentModel  
  9. open System.Drawing  
  10. let graphicform = new Form(Text="Draw Circle",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 250),StartPosition=FormStartPosition.CenterScreen)  
  11. //creates our control  
  12. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 200))  
  13. graphicform.Paint.Add(fun draw->  
  14.   
  15. let brush=new SolidBrush(Color.Blue)  
  16. draw.Graphics.FillEllipse(brush,0.0f,0.0f,100.0f,100.0f))  
  17.   
  18. graphicform.Controls.Add(exitbutton)  
  19. //executes our application  
  20. Application.Run(graphicform)  

Display the Date or Time from a DateTime Object

There are several ways on how to retrieve the date or time part from a datetime object, here are the few methods that I discover through research and experimentation:

1. Using Substring

Display the time part using Substring:
  1. // Learn more about F# at http://fsharp.net  
  2. //use the F# library  
  3. open System  
  4. //use this to enable the intellisense. Very helpful in coding your application  
  5. open System.Drawing   
  6. //specify the location of the Form classes  
  7. open System.Windows.Forms  
  8. let ffont=new Font("Verdana", 14.5F,FontStyle.Regular, GraphicsUnit.Point)  
  9. //creates a form  
  10. let timerform=new Form(Text="Display Time Part",StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. let timelabel=new Label(Location=new System.Drawing.Point(20,40),BorderStyle=BorderStyle.FixedSingle,AutoSize=true)  
  12.   
  13. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 220),AutoSize=true)  
  14. //create a timer object and set its interval to 1 second  
  15. //by default timer are disabled so you'll need to enable it  
  16. let timer1=new Timer(Interval=1000,Enabled=true)  
  17. timelabel.Font<-ffont  
  18. //change it every 1 min second  
  19. timer1.Tick.Add(fun time->  
  20. //assigns the current date and time to a variable  
  21. let datetime=Convert.ToString(System.DateTime.Now)  
  22. //retrieves the value of the datetime variable  
  23. //starting from the 11th character  
  24. let timepart=datetime.Substring(10)  
  25. //display the time  
  26. timelabel.Text<-timepart)  
  27.                   
  28. //adds the exit button to our form  
  29. timerform.Controls.Add(timelabel)  
  30. timerform.Controls.Add(exitbutton)  
  31. //when the exit button is clicked  
  32. exitbutton.Click.Add(fun quit->  
  33. //stops the time  
  34. timer1.Stop()  
  35. //close the form  
  36. timerform.Close())                     
  37. //show our form  
  38. timerform.Show()  
  39. //execute our application  
  40. Application.Run(timerform)  

Display the time part using the substring function:
  1. // Learn more about F# at http://fsharp.net  
  2. //use the F# library  
  3. open System  
  4. //use this to enable the intellisense. Very helpful in coding your application  
  5. open System.Drawing   
  6. //specify the location of the Form classes  
  7. open System.Windows.Forms  
  8. let ffont=new Font("Verdana", 14.5F,FontStyle.Regular, GraphicsUnit.Point)  
  9. //creates a form  
  10. let dateform=new Form(Text="Display Date Part",StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. //use the random function to generate random numbers  
  12. let datelabel=new Label(Location=new System.Drawing.Point(20,40),BorderStyle=BorderStyle.FixedSingle,AutoSize=true)  
  13.   
  14. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 220),AutoSize=true)  
  15.   
  16. datelabel.Font<-ffont  
  17. dateform.Load.Add(fun time->  
  18. //assigns the current date and time to the datetime variable  
  19. let datetime=Convert.ToString(System.DateTime.Now)  
  20. //retrieves the text from the datetime variable staring from the first  
  21. //character to the 11th character  
  22. let datepart=datetime.Substring(0,10)  
  23. //display the current time  
  24. datelabel.Text<-datepart)  
  25.                   
  26. //adds the exit button to our form  
  27. dateform.Controls.Add(datelabel)  
  28. dateform.Controls.Add(exitbutton)  
  29. //when the exit button is clicked  
  30. exitbutton.Click.Add(fun quit->dateform.Close())                     
  31. //execute our application  
  32. Application.Run(dateform)  


2. Using Remove

Display the time part using Remove:
  1. // Learn more about F# at http://fsharp.net  
  2. //use the F# library  
  3. open System  
  4. //use this to enable the intellisense. Very helpful in coding your application  
  5. open System.Drawing   
  6. //specify the location of the Form classes  
  7. open System.Windows.Forms  
  8. let ffont=new Font("Verdana", 14.5F,FontStyle.Regular, GraphicsUnit.Point)  
  9. //creates a form  
  10. let timerform=new Form(Text="Display Time Part",StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. let timelabel=new Label(Location=new System.Drawing.Point(20,40),BorderStyle=BorderStyle.FixedSingle,AutoSize=true)  
  12.   
  13. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 220),AutoSize=true)  
  14. //create a timer object and set its interval to 1 second  
  15. //by default timer are disabled so you'll need to enable it  
  16. let timer1=new Timer(Interval=1000,Enabled=true)  
  17. timelabel.Font<-ffont  
  18. //change it every 1 min second  
  19. timer1.Tick.Add(fun time->  
  20. //assigns the current date and time to the datetime variable  
  21. let datetime=Convert.ToString(System.DateTime.Now)  
  22. //removes the first 11 characters from the datetime variable  
  23. let timepart=datetime.Remove(0,10)  
  24. //display the current time  
  25. timelabel.Text<-timepart)  
  26.                   
  27. //adds the exit button to our form  
  28. timerform.Controls.Add(timelabel)  
  29. timerform.Controls.Add(exitbutton)  
  30. //when the exit button is clicked  
  31. exitbutton.Click.Add(fun quit->  
  32. //stops the time  
  33. timer1.Stop()  
  34. //close the form  
  35. timerform.Close())                     
  36. //show our form  
  37. timerform.Show()  
  38. //execute our application  
  39. Application.Run(timerform)  

Display the date part using the Remove function:
  1. // Learn more about F# at http://fsharp.net  
  2. //use the F# library  
  3. open System  
  4. //use this to enable the intellisense. Very helpful in coding your application  
  5. open System.Drawing   
  6. //specify the location of the Form classes  
  7. open System.Windows.Forms  
  8. let ffont=new Font("Verdana", 14.5F,FontStyle.Regular, GraphicsUnit.Point)  
  9. //creates a form  
  10. let dateform=new Form(Text="Display Date Part",StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  11. //use the random function to generate random numbers  
  12. let datelabel=new Label(Location=new System.Drawing.Point(20,40),BorderStyle=BorderStyle.FixedSingle,AutoSize=true)  
  13.   
  14. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 220),AutoSize=true)  
  15.   
  16. datelabel.Font<-ffont  
  17. dateform.Load.Add(fun time->  
  18. //assigns the current date and time to the datetime variable  
  19. let datetime=Convert.ToString(System.DateTime.Now)  
  20. //removes the text from the datetime variable staring from the 11 character  
  21. let datepart=datetime.Remove(10)  
  22. //display the current time  
  23. datelabel.Text<-datepart)  
  24.                   
  25. //adds the exit button to our form  
  26. dateform.Controls.Add(datelabel)  
  27. dateform.Controls.Add(exitbutton)  
  28. //when the exit button is clicked  
  29. exitbutton.Click.Add(fun quit->dateform.Close())                     
  30. //execute our application  
  31. Application.Run(dateform)  

SystemSounds in F#

To play a system sound in Visual F#, use the SystemSounds object. For a simple example on using the SystemSounds object, try the following:


  1. // Learn more about F# at http://fsharp.net  
  2. //use the f# standard library  
  3. open System  
  4. //use media classes  
  5. open System.Media  
  6. //specify the memory location of the classes used in drawing objects  
  7. //required to draw the listbox item text  
  8. open System.Drawing  
  9. //specify the location of the form class  
  10. open System.Windows.Forms  
  11. //creates a form and assign a "Play System Sounds" caption to it  
  12. let soundform=new Form(Text="Play System Sounds",StartPosition=FormStartPosition.CenterScreen,AutoScaleMode=AutoScaleMode.Font)  
  13. //creates a label and set its Text to “Count”  
  14. let lbl=new Label(Text="System sounds:", Location=new System.Drawing.Point(20,10),AutoSize=true)  
  15. //makes a listbox  
  16. let soundlistbox=new ListBox(Sorted=true,Location=new System.Drawing.Point(20,30),FormattingEnabled=true)  
  17. //adds an item to the listbox when the form is loaded  
  18. soundform.Load.Add(fun items->  
  19.      //adds the items and ignore the passed index position values  
  20.                     soundlistbox.Items.Add("Asterisk")|>ignore  
  21.                     soundlistbox.Items.Add("Beep")|>ignore  
  22.                     soundlistbox.Items.Add("Exclaimation")|>ignore  
  23.                     soundlistbox.Items.Add("Hand")|>ignore  
  24.                     soundlistbox.Items.Add("Question")|>ignore)  
  25. soundlistbox.Click.Add(fun playsound->  
  26.                     if soundlistbox.SelectedIndex=0 then  
  27.                         SystemSounds.Asterisk.Play()  
  28.                         MessageBox.Show("Asterisk""System Sounds", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)|>ignore  
  29.                     if soundlistbox.SelectedIndex=1 then  
  30.                         SystemSounds.Beep.Play()  
  31.                         MessageBox.Show("Beep""System Sounds", MessageBoxButtons.OK)|>ignore  
  32.                     if soundlistbox.SelectedIndex=2 then  
  33.                         SystemSounds.Exclamation.Play()  
  34.                         MessageBox.Show("Exclaimation""System Sounds", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)|>ignore  
  35.                     if soundlistbox.SelectedIndex=3 then  
  36.                         SystemSounds.Hand.Play()  
  37.                         MessageBox.Show("Hand""System Sounds", MessageBoxButtons.OK, MessageBoxIcon.Hand)|>ignore  
  38.                     if soundlistbox.SelectedIndex=4 then  
  39.                        SystemSounds.Question.Play()  
  40.                         MessageBox.Show("Question""System Sounds", MessageBoxButtons.OK, MessageBoxIcon.Question)|>ignore)   
  41.                                              
  42. //displays the label to our form  
  43. soundform.Controls.Add(lbl)        
  44. //adds the listbox to our form      
  45. soundform.Controls.Add(soundlistbox)             
  46. soundform.Show()  
  47. Application.Run(soundform)  

This will generate the following output:

Adding space to a concatenated String

There are several ways to add space to a contanated string in Visual F#:

1.Using the Tab Escape Character

Syntax:
  1. “text1” + “\t” + “textn”  

For instance:
  1. Trace.WriteLine("Adding" +”\t”+ “Space”)  

This will display “Adding Space” with 5-6 spaces in between in the output window. You can also use the unicode equivalent of tab which is \u0009. For example:
  1. Trace.WriteLine("Adding" +”\u0009”+ “Space”)  
2. Typing a space or “ “ between the concatenated strings
Syntax:
  1. “text1” + “ ” + “textn”  

For instance:
  1. Trace.WriteLine("Adding" +” ”+ “Space”)  
You can also use the unicode equivalent of space which is \u0032. For example:
  1. Trace.WriteLine("Adding" +”\u0032”+ “Space”)  
3. Using the Convert.ToChar() string manipulation function
Convert.ToChar converts a specified key code to character.
The key code for tab is 9 while Spacebar has 32.

Syntax:
  1. Convert.ToChar(key code)  
Examples:
  1. //backspace key  
  2. Trace.WriteLine(Convert.ToString(Convert.ToChar(8)))  
  3. //enter key  
  4. Trace.WriteLine(Convert.ToString(Convert.ToChar(13)))  
  5. //adds space to a concatenated string  
  6. Trace.WriteLine(“Adding” + Convert.ToString(Convert.ToChar(32)) + “Space” )  

For a simple example of application that adds space to a concatenated string:

1. Click Start>All Programs>Microsoft Visual Studio 2008>Microsoft Visual Studio 2008.

2. Click File>New>Project>Select Visual F# in the project types>Select F# application in the Visual Studio installed templates category.

3. Click the Project menu>Add reference>Click the .Net tab>Locate then double-click System.Windows.Forms. Do step 3 again and this time, select System.Drawing from the .Net tab.

4. Enter the following code after the line “// Learn more about F# at http://fsharp.net “:

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the namespace memory location of the classes that  
  3. //will be used in our application  
  4. open System  
  5. open System.Diagnostics  
  6. open System.Windows.Forms  
  7. open System.Drawing  
  8. //creates our form  
  9. let myform= new Form(Text="Adding Space")  
  10. //creates our controls    
  11. let label1=new Label(Text="Firstname:",Location=new System.Drawing.Point(0, 10),AutoSize=true)  
  12. let label2=new Label(Text="Lastname:",Location=new System.Drawing.Point(0, 50),AutoSize=true)  
  13. let fnametextbox=new TextBox(Location=new System.Drawing.Point(100,10),BorderStyle=BorderStyle.FixedSingle)  
  14. let lnametextbox=new TextBox(Location=new System.Drawing.Point(100,50),BorderStyle=BorderStyle.FixedSingle)  
  15. let okbutton=new Button(Text="Ok", Location=new System.Drawing.Point(120, 170))  
  16. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 170))  
  17. myform.Controls.Add(label1)  
  18. myform.Controls.Add(label2  
  19. myform.Controls.Add(fnametextbox)  
  20. myform.Controls.Add(lnametextbox)  
  21. myform.Controls.Add(okbutton)  
  22. myform.Controls.Add(exitbutton)  
  23. myform.Click.Add(fun space->  
  24. //display our text in the ouput window  
  25. Trace.WriteLine("Adding Spaces")  
  26. Trace.WriteLine(label1.Text + "\u0009" + fnametextbox.Text)  
  27. Trace.WriteLine(label2.Text + "\u0009" + lnametextbox.Text))  
  28.   
  29. //execute our application  
  30. myform.Show()  
  31. Application.Run(myform)  

Gradient and Textured Form in Visual F#

To create a gradient form in Visual F#, simply use a gradient brush and use that brush to draw a rectangle that will cover the whole form area. To create a LinearGradientBrush, use the following syntax:
  1. let newbrush=new LinearGradientBrush(brushpoint,color1,color2,strokeangle)  
For instance:
  1. let newbrush=new LinearGradientBrush(rect,Color.Green,Color.YellowGreen,45.0F)  
Follow these steps to create a gradient form using the LinearGradientBrush drawing method:

1. Click Start>All Programs>Microsoft Visual Studio 2008>Microsoft Visual Studio 2008.

2. Click File>New>Project>Select Visual F# in the project types>Select F# application in the Visual Studio installed templates category.

3. Click the Project menu>Add reference>Click the .Net tab>Locate then double-click System.Windows.Forms. Do step 3 again and this time, select System.Drawing from the .Net tab.

4. Enter the following code after the line “// Learn more about F# at http://fsharp.net “:

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the namespace memory location of the classes that  
  3. //will be used in our application  
  4. open System  
  5. open System.Windows.Forms  
  6. open System.Drawing  
  7. open System.Drawing.Drawing2D  
  8. //creates our form  
  9. let myform= new Form(Text="Add Gradient Background")  
  10. //create a rectangle  
  11. //change its upper left x and y coordinates to 0,0  
  12. //sets it width and height to the width and height of the form  
  13. let rect=new Rectangle(0,0,myform.Width,myform.Height)  
  14. //creates a gradient brush  
  15. let newbrush=new LinearGradientBrush(rect,Color.Green,Color.YellowGreen,45.0F)  
  16. //paints our form with a solid and filled rectangle  
  17. myform.Paint.Add(fun fillrect->fillrect.Graphics.FillRectangle(newbrush,rect))   
  18. //executes our application  
  19. myform.Show()  
  20. Application.Run(myform)  

This will display the following output:



To create a textured form, use a TextureBrush to draw a rectangle that will cover the whole form area then display that rectangle on your form.

For instance:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the namespace memory location of the classes that  
  3. //will be used in our application  
  4. open System  
  5. open System.Windows.Forms  
  6. open System.Drawing  
  7. open System.Drawing.Drawing2D  
  8.   
  9. //creates our form  
  10. let myform= new Form(Text="Add Textured Background")  
  11. //draws a rectangle with the same width and height as our form  
  12. let drawrect=new Rectangle(0,0,myform.Width,myform.Height)  
  13. //creates a texturedbrush using a windows default image  
  14. //tile the image Vertically and Horizontally  
  15. let newbrush=new TextureBrush(new Bitmap("C:\Windows\Zapotec.bmp"),WrapMode=WrapMode.TileFlipXY)  
  16. //applies the brush in drawing our rectangle  
  17. myform.Paint.Add(fun fillrect->fillrect.Graphics.FillRectangle(newbrush, drawrect))   
  18. //executes our application  
  19. myform.Show()  
  20. Application.Run(myform)  

Add navigational buttons to a database application without using a BindingNavigator

On my previous post, we were able to add a navigational button to our application by using a BindingNavigator, today, we will do everything manually. To add a navigational button by hand, all you need to do is to bind your controls using this method and increment or decrement the Row index number to navigate around your records. This method is slightly similar to the methods used by most developers in adding navigational buttons to VB.net database applications.

For the sake of example, follow these steps(I assume here that you have already created a database file named “dbEmployee” and a table named “tblEmployee”):

1. Click Start>All Programs>Microsoft Visual Studio 2008>Microsoft Visual Studio 2008.

2. Click File>New>Project>Select Visual F# in the project types>Select F# application in the Visual Studio installed templates category.

3. Click the Project menu>Add reference>Click the .Net tab>Locate then double-click System.Windows.Forms. Do step 3 again and this time, select System.Drawing and System.Data from the .Net tab.

4. Enter the following code after the line “// Learn more about F# at http://fsharp.net “:

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System  
  5. open System.Windows.Forms  
  6. open System.Data  
  7. open System.Drawing  
  8. open System.Data.OleDb  
  9. //creates a font  
  10. let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)    
  11. //creates a connection object  
  12. let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;  
  13.   Data Source=C:\Documents and Settings\Administrator\My Documents\dbEmployee.mdb")  
  14.  //creates an OleDbDataAdapter  
  15. let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblEmployee", oleconn)  
  16. let deletecommand=new System.Data.OleDb.OleDbCommand()  
  17.   
  18. //generates a dataset  
  19. let dataset11 = new DataSet()  
  20. //fills the dataset with recod values  
  21. dataadpter.Fill(dataset11,"tblEmployee")|>ignore  
  22. //creates a form  
  23. let dataform = new Form(Text="Add Navigational Buttons Manually",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)  
  24. //creates our controls  
  25. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(200, 170))    
  26. let label1=new Label(Text="Employee number:",Location=new System.Drawing.Point(0, 10),AutoSize=true)  
  27. let label2=new Label(Text="Firstname:",Location=new System.Drawing.Point(0, 50),AutoSize=true)  
  28. let label3=new Label(Text="Lastname:",Location=new System.Drawing.Point(0,100),AutoSize=true)  
  29. let emplabel=new Label(Location=new System.Drawing.Point(140,10),BorderStyle=BorderStyle.FixedSingle)  
  30. let fnamelabel=new Label(Location=new System.Drawing.Point(100,50),BorderStyle=BorderStyle.FixedSingle)  
  31. let lnamelabel=new Label(Location=new System.Drawing.Point(100,100),BorderStyle=BorderStyle.FixedSingle)  
  32. let topbutton=new Button(Text="Top", Location=new System.Drawing.Point(40, 170))  
  33. let bottombutton=new Button(Text="Bottom", Location=new System.Drawing.Point(120, 170))  
  34. //assings the font to our form  
  35. dataform.Font<-ffont  
  36. //adds the controls to our form  
  37. dataform.Controls.Add(exitbutton)  
  38. dataform.Controls.Add(label1)  
  39. dataform.Controls.Add(label2)  
  40. dataform.Controls.Add(label3)  
  41. dataform.Controls.Add(emplabel)  
  42. dataform.Controls.Add(fnamelabel)  
  43. dataform.Controls.Add(lnamelabel)  
  44. dataform.Controls.Add(topbutton)  
  45. dataform.Controls.Add(bottombutton)  
  46.   
  47. //binds the fieldnames to our label  
  48. emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(0))  
  49. fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(1))  
  50. lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(2))  
  51.   
  52. //when the topbutton is clicked  
  53. //assigns 0 rowindexnumber value causing the   
  54. //first record to be displayed  
  55. topbutton.Click.Add(fun top->  
  56. emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(0))  
  57. fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(1))  
  58. lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(2)))  
  59.   
  60. //when the bottombutton is clicked  
  61. //assign the index number of the last row as a rowindexnumer  
  62. //since we only have two records on our table  
  63. //so the index number of the last row is understood to be 1  
  64. //when manipulating large number of records, i suggest using  
  65. //dataset11.Tables.["tblEmployee"].Rows.Count() to  
  66. //automatically count the number of records  
  67.   
  68. bottombutton.Click.Add(fun bottom->  
  69. emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(1).Item(0))  
  70. fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(1).Item(1))  
  71. lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(1).Item(2)))  
  72.   
  73. //when the exit button is clicked  
  74. exitbutton.Click.Add(fun exit->  
  75. //close the form and dataconnection  
  76.                     dataform.Close()  
  77.                     oleconn.Close())  
  78.   
  79. //executes our application  
  80. dataform.Show()  
  81. Application.Run(dataform)  

5. This will display the following output:



6. Simple...right?

Yet another way of binding a control to a field name in Visual F#

On my last post, I’ve shown you how to bind a record value to a control using the DataBindings method. Another way of binding a control to a fieldname is by using Text property of a control and assigning the dataset collection properties as its value:

Syntax:

  1. controlobjvariable.Text<- (datasetname.Tables.["tablename"].Rows.Item(rowindexnumber).Item(columnindexnumber))  
For instance:
  1. emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(0))  
The rowindexnumber of the first record on your table is 0, the second record is 1 and so on. Same goes with the columnindexnumber. For a simple example of application that uses the binding method above, follow these steps(I assume here that you have already created a database file named “dbEmployee” and a table named “tblEmployee”):
1. Click Start>All Programs>Microsoft Visual Studio 2008>Microsoft Visual Studio 2008.
2. Click File>New>Project>Select Visual F# in the project types>Select F# application in the Visual Studio installed templates category.
3. Click the Project menu>Add reference>Click the .Net tab>Locate then double-click System.Windows.Forms. Do step 3 again and this time, select System.Drawing and System.Data from the .Net tab.
4. Enter the following code after the line “// Learn more about F# at http://fsharp.net “:
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System  
  5. open System.Windows.Forms  
  6. open System.Data  
  7. open System.Drawing  
  8. open System.Data.OleDb  
  9. //creates a font  
  10. let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)    
  11. //creates a connection object  
  12. let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;  
  13.   Data Source=C:\Documents and Settings\Administrator\My Documents\dbEmployee.mdb")  
  14.  //creates an OleDbDataAdapter  
  15. let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblEmployee", oleconn)  
  16. let deletecommand=new System.Data.OleDb.OleDbCommand()  
  17.   
  18. //generates a dataset  
  19. let dataset11 = new DataSet()  
  20. //fills the dataset with recod values  
  21. dataadpter.Fill(dataset11,"tblEmployee")|>ignore  
  22. //creates a form  
  23. let dataform = new Form(Text="Bind Form Control Part 2",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)  
  24. //creates our controls  
  25. let exitbutton=new Button(Text="Exit", Location=new System.Drawing.Point(190, 170))    
  26. let label1=new Label(Text="Employee number:",Location=new System.Drawing.Point(0, 10),AutoSize=true)  
  27. let label2=new Label(Text="Firstname:",Location=new System.Drawing.Point(0, 50),AutoSize=true)  
  28. let label3=new Label(Text="Lastname:",Location=new System.Drawing.Point(0,100),AutoSize=true)  
  29. let emplabel=new Label(Location=new System.Drawing.Point(140,10),BorderStyle=BorderStyle.FixedSingle)  
  30. let fnamelabel=new Label(Location=new System.Drawing.Point(100,50),BorderStyle=BorderStyle.FixedSingle)  
  31. let lnamelabel=new Label(Location=new System.Drawing.Point(100,100),BorderStyle=BorderStyle.FixedSingle)  
  32. //assings the font to our form  
  33. dataform.Font<-ffont  
  34. //adds the controls to our form  
  35. dataform.Controls.Add(exitbutton)  
  36. dataform.Controls.Add(label1)  
  37. dataform.Controls.Add(label2)  
  38. dataform.Controls.Add(label3)  
  39. dataform.Controls.Add(emplabel)  
  40. dataform.Controls.Add(fnamelabel)  
  41. dataform.Controls.Add(lnamelabel)  
  42.   
  43. //binds the fieldnames to our label  
  44. emplabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(0))  
  45. fnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(1))  
  46. lnamelabel.Text<-Convert.ToString(dataset11.Tables.["tblEmployee"].Rows.Item(0).Item(2))  
  47.   
  48. //when the exit button is clicked  
  49. exitbutton.Click.Add(fun exit->  
  50. //close the form and dataconnection  
  51.                     dataform.Close()  
  52.                     oleconn.Close())  
  53.   
  54. //executes our application  
  55. dataform.Show()  
  56. Application.Run(dataform)  
5. This will display the following output:

Manipulating an Image Data in Visual F#

To manipulate an image data, simply add an oleobject fieldname on your table and insert a bitmap image to it. To display the image on your form, use a picturebox control then bind your oleobject fieldname to it using the following syntax:
  1. Pictureboxobjname.DataBindings.Add(new Binding(pictureboxproperty,datasource,fieldname))  
For instance:
  1. appico.DataBindings.Add(new Binding("Image",bindingsource,"oleapplogo",true))  
The last boolean parameter enables the control formatting. We also use the Image property instead of the usual Text for the fact that it is the property used to display an image on your form.

Before proceding to the steps below, I want you to make an Ms-Access 2003 or 2007 database file named “dbApplication”. Create a table inside it and name it “tblApplication”. Use the following specifications:



Chrappname Text Handles the application name
Oleapplogo OLE Object Handles the application ico

After creating your table, you can add appropriate values to it for instance:




chrappname oleapplogo
PHP Bitmap Image
Apache Bitmap Image

Bitmap Image refers the the Bitmap Object that you have inserted using the Paste From Ms-Paint command.

After creating the table and adding appropriate values to it.We are now ready for our sample application. Just follow these steps:

1. Click Start>All Programs>Microsoft Visual Studio 2008>Microsoft Visual Studio 2008.

2. Click File>New>Project>Select Visual F# in the project types>Select F# application in the Visual Studio installed templates category.

3. Click the Project menu>Add reference>Click the .Net tab>Locate then double-click System.Windows.Forms. Do step 3 again and this time, select System.Drawing and System.Data from the .Net tab.

4. Enter the following code after the line “// Learn more about F# at http://fsharp.net “:

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System  
  5. open System.Windows.Forms  
  6. open System.Data  
  7. open System.Drawing  
  8. //creates a font  
  9. let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)    
  10. //creates a connection object  
  11. let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;  
  12.   Data Source=C:\Documents and Settings\station 2\My Documents\dbApplication.mdb")  
  13.  //creates an OleDbDataAdapter  
  14. let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblApplication", oleconn)  
  15. //generates a dataset  
  16. let dataset11 = new DataSet()  
  17. //fills the dataset with recod values  
  18. dataadpter.Fill(dataset11,"tblApplication")|>ignore  
  19. //creates a form  
  20. let dataform = new Form(Text="Manipulate Image Data",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)  
  21. //creates our controls    
  22. let label1=new Label(Text="App. name:",Location=new System.Drawing.Point(0, 10),AutoSize=true)  
  23. let label2=new Label(Text="Icon:",Location=new System.Drawing.Point(0, 50),AutoSize=true)  
  24. let appnamelabel=new Label(Location=new System.Drawing.Point(140,10),BorderStyle=BorderStyle.FixedSingle)  
  25. let appico=new PictureBox(SizeMode=PictureBoxSizeMode.StretchImage,Location=new System.Drawing.Point(140,50))  
  26.   
  27. let bindingsource=new BindingSource()  
  28. //creates a binding navigator  
  29. //this will allow us to add navigational buttons to our data grid  
  30. let bindingnav=new BindingNavigator(Dock=DockStyle.None,Location=new System.Drawing.Point(100, 170))  
  31. //creates a toolstrip buttons for our binding navigator  
  32. let movefirst=new ToolStripButton(Text="Top")  
  33. let moveprev=new ToolStripButton(Text="Prev")  
  34. let movenext=new ToolStripButton(Text="Next")  
  35. let movelast=new ToolStripButton(Text="Bottom")  
  36. let exitbutton=new ToolStripButton(Text="Exit")  
  37. //adds the toolstripbuttons to our binding navigator  
  38. bindingnav.Items.Add(movefirst)|>ignore  
  39. bindingnav.Items.Add(moveprev)|>ignore  
  40. bindingnav.Items.Add(movenext)|>ignore  
  41. bindingnav.Items.Add(movelast)|>ignore  
  42. bindingnav.Items.Add(exitbutton)|>ignore  
  43. //adds a function to each buttons  
  44. bindingnav.MoveFirstItem<-movefirst  
  45. bindingnav.MoveNextItem<-movenext  
  46. bindingnav.MovePreviousItem<-moveprev  
  47. bindingnav.MoveLastItem<-movelast  
  48. exitbutton.Click.Add(fun exit->  
  49. //close the form and dataconnection  
  50.                     dataform.Close()  
  51.                     oleconn.Close())  
  52. //assigns the dataset name as a bindingsource datasource  
  53. bindingsource.DataSource<-dataset11  
  54. //assigns our table as a binding source datamember  
  55. bindingsource.DataMember<-"tblApplication"  
  56. //assigns the bindingsource name as a binding navigators  
  57. //bindingsource value  
  58. bindingnav.BindingSource<-bindingsource  
  59. //opens the connection  
  60. oleconn.Open()  
  61. //assings the font to our form  
  62. dataform.Font<-ffont  
  63. //adds the controls to our form  
  64. dataform.Controls.Add(label1)  
  65. dataform.Controls.Add(label2)  
  66. dataform.Controls.Add(appnamelabel)  
  67. dataform.Controls.Add(appico)  
  68.   
  69. dataform.Controls.Add(bindingnav)  
  70. //binds the fieldnames to our label  
  71. appnamelabel.DataBindings.Add(new Binding("Text",bindingsource,"chrappname"))  
  72. appico.DataBindings.Add(new Binding("Image",bindingsource,"oleapplogo",true))  
  73. //executes our application  
  74. dataform.Show()  
  75. Application.Run(dataform)  
5. Click the run icon to execute your application. You should now see an output similar to the following screen shot: 6. Here’s another version of the code above without BindingSource and BindingNavigator.
  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System  
  5. open System.Windows.Forms  
  6. open System.Data  
  7. open System.Drawing  
  8. //creates a font  
  9. let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)    
  10. //creates a connection object  
  11. let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;  
  12.   Data Source=C:\Documents and Settings\station 2\My Documents\dbApplication.mdb")  
  13.  //creates an OleDbDataAdapter  
  14. let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblApplication", oleconn)  
  15. //generates a dataset  
  16. let dataset11 = new DataSet()  
  17. //fills the dataset with recod values  
  18. dataadpter.Fill(dataset11,"tblApplication")|>ignore  
  19. //creates a form  
  20. let dataform = new Form(Text="Manipulate Image Data",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)  
  21. //creates our controls    
  22. let label1=new Label(Text="App. name:",Location=new System.Drawing.Point(0, 10),AutoSize=true)  
  23. let label2=new Label(Text="Icon:",Location=new System.Drawing.Point(0, 50),AutoSize=true)  
  24. let appnamelabel=new Label(Location=new System.Drawing.Point(140,10),BorderStyle=BorderStyle.FixedSingle)  
  25. let appico=new PictureBox(SizeMode=PictureBoxSizeMode.StretchImage,Location=new System.Drawing.Point(140,50))  
  26. //opens the connection  
  27. oleconn.Open()  
  28. //assings the font to our form  
  29. dataform.Font<-ffont  
  30. //adds the controls to our form  
  31. dataform.Controls.Add(label1)  
  32. dataform.Controls.Add(label2)  
  33. dataform.Controls.Add(appnamelabel)  
  34. dataform.Controls.Add(appico)  
  35. //binds the fieldnames to our label  
  36. appnamelabel.DataBindings.Add(new Binding("Text",dataset11,"tblApplication.chrappname"))  
  37. appico.DataBindings.Add(new Binding("Image",dataset11,"tblApplication.oleapplogo",true))  
  38. //executes our application  
  39. dataform.Show()  
  40. Application.Run(dataform)  
For more sketchy tutorials on Visual F# visit Microsoft F# Developer Center.

Adding navigational Buttons to your database application

The fastest way to add navigational buttons to your database application is to use a BindingNavigator. If you are not yet familiar with Binding Navigator, I suggest reading this post first before proceeding to the steps below:

Before the Database Connection and Binding process I want you to make an Ms-Access database file named “dbEmployee” containing a table named “tblEmployee”. Use the following specifications:

Field NameData Type Description
chrempno text Handles employee id
chrfnametext Handles employee’s name
chrlname text Holds employee’s last name


After designing the structure of your table, you can enter appropriate values for each field. For instance:

chrempnochrfnameChrlname
1John Doe
2Jean Doe


Now that we are done creating a table, we can now link to it by using OleDbDataAdapter in Visual F#:


1. Click Start>All Programs>Microsoft Visual Studio 2008>Microsoft Visual Studio 2008.

2. Click File>New>Project>Select Visual F# in the project types>Select F# application in the Visual Studio installed templates category.

3. Click the Project menu>Add reference>Click the .Net tab>Locate then double-click System.Windows.Forms. Do step 3 again and this time, select System.Drawing and System.Data from the .Net tab.

4. Enter the following code after the line “// Learn more about F# at http://fsharp.net “:

  1. // Learn more about F# at http://fsharp.net  
  2. //specifies the memory location of the class files  
  3. //that will be needed in our application  
  4. open System  
  5. open System.Windows.Forms  
  6. open System.Data  
  7. open System.Drawing  
  8. //creates a font  
  9. let ffont=new Font("Verdana", 9.75F,FontStyle.Regular, GraphicsUnit.Point)    
  10. //creates a connection object  
  11. let oleconn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;  
  12.   Data Source=C:\Documents and Settings\station 2\My Documents\dbEmployee.mdb")  
  13.  //creates an OleDbDataAdapter  
  14. let dataadpter = new System.Data.OleDb.OleDbDataAdapter("Select * from tblEmployee", oleconn)  
  15. //generates a dataset  
  16. let dataset11 = new DataSet()  
  17. //fills the dataset with recod values  
  18. dataadpter.Fill(dataset11,"tblEmployee")|>ignore  
  19. //creates a form  
  20. let dataform = new Form(Text="Add Navigational Buttons",AutoScaleDimensions=new System.Drawing.SizeF(60.0F, 13.0F),ClientSize=new System.Drawing.Size(300, 200),StartPosition=FormStartPosition.CenterScreen)  
  21. //creates our controls    
  22. let label1=new Label(Text="Employee number:",Location=new System.Drawing.Point(0, 10),AutoSize=true)  
  23. let label2=new Label(Text="Firstname:",Location=new System.Drawing.Point(0, 50),AutoSize=true)  
  24. let label3=new Label(Text="Lastname:",Location=new System.Drawing.Point(0,100),AutoSize=true)  
  25. let emplabel=new Label(Location=new System.Drawing.Point(140,10),BorderStyle=BorderStyle.FixedSingle)  
  26. let fnamelabel=new Label(Location=new System.Drawing.Point(100,50),BorderStyle=BorderStyle.FixedSingle)  
  27. let lnamelabel=new Label(Location=new System.Drawing.Point(100,100),BorderStyle=BorderStyle.FixedSingle)  
  28. let bindingsource=new BindingSource()  
  29. //creates a binding navigator  
  30. //this will allow us to add navigational buttons to our data grid  
  31. let bindingnav=new BindingNavigator(Dock=DockStyle.None,Location=new System.Drawing.Point(100, 170))  
  32. //creates a toolstrip buttons for our binding navigator  
  33. let movefirst=new ToolStripButton(Text="Top")  
  34. let moveprev=new ToolStripButton(Text="Prev")  
  35. let movenext=new ToolStripButton(Text="Next")  
  36. let movelast=new ToolStripButton(Text="Bottom")  
  37. let exitbutton=new ToolStripButton(Text="Exit")  
  38. //adds the toolstripbuttons to our binding navigator  
  39. bindingnav.Items.Add(movefirst)|>ignore  
  40. bindingnav.Items.Add(moveprev)|>ignore  
  41. bindingnav.Items.Add(movenext)|>ignore  
  42. bindingnav.Items.Add(movelast)|>ignore  
  43. bindingnav.Items.Add(exitbutton)|>ignore  
  44. //adds a function to each buttons  
  45. bindingnav.MoveFirstItem<-movefirst  
  46. bindingnav.MoveNextItem<-movenext  
  47. bindingnav.MovePreviousItem<-moveprev  
  48. bindingnav.MoveLastItem<-movelast  
  49. exitbutton.Click.Add(fun exit->  
  50. //close the form and dataconnection  
  51.                     dataform.Close()  
  52.                     oleconn.Close())  
  53. //assigns the dataset name as a bindingsource datasource  
  54. bindingsource.DataSource<-dataset11  
  55. //assigns our table as a binding source datamember  
  56. bindingsource.DataMember<-"tblEmployee"  
  57. //assigns the bindingsource name as a binding navigators  
  58. //bindingsource value  
  59. bindingnav.BindingSource<-bindingsource  
  60. //opens the connection  
  61. oleconn.Open()  
  62. //assings the font to our form  
  63. dataform.Font<-ffont  
  64. //adds the controls to our form  
  65. dataform.Controls.Add(label1)  
  66. dataform.Controls.Add(label2)  
  67. dataform.Controls.Add(label3)  
  68. dataform.Controls.Add(emplabel)  
  69. dataform.Controls.Add(fnamelabel)  
  70. dataform.Controls.Add(lnamelabel)  
  71. dataform.Controls.Add(bindingnav)  
  72. //binds the fieldnames to our label  
  73. emplabel.DataBindings.Add(new Binding("Text",bindingsource,"chrempno"))  
  74. fnamelabel.DataBindings.Add(new Binding("Text",bindingsource,"chrfname"))  
  75. lnamelabel.DataBindings.Add(new Binding("Text",bindingsource,"chrlname"))  
  76. //executes our application  
  77. dataform.Show()  
  78. Application.Run(dataform)  
5. Click the run icon to execute your application. You should now see an output similar to the following screen shot: For more sketchy tutorials on Visual F# visit Microsoft F# Developer Center.