Gambas/Branch

Back to Gambas

What are branches in a program?
A branch is a point at which your program must make a choice. With these structures, it is possible to make programs that can have multiple outcomes. There are mainly two branching methods:
 * if then and ist variations
 * select case

If...Then statement
The if then branch works quite the same as it is used in natural language. If something is true, then make something. If it is not true then just continue.

Try this little example: You just need a command button on your form to get it going. The output is shown in the terminal window.

PUBLIC SUB Button1_Click k AS Integer FOR k = 1 TO 10000 IF k = 5000 THEN PRINT "5000 has been reached !" NEXT END

Try to alter the program so that the output is shown in a textbox. You have to add a textbox to your form. You will find it with F6 in your toolbox. Then you have to change the code, so that the print command is exchanged.

PUBLIC SUB Button1_Click k AS Integer FOR k = 1 TO 10000 IF k = 5000 THEN textbox1.text = "5000 has been reached !" NEXT END

If...Then...Else...End if
You can modify the if-then construction by adding some other commands like else and end if. Here is another example with an else and end if command in it. You just need a command button on your form to get it going.

PUBLIC SUB Button1_Click k AS Integer FOR k = 1 TO 6000 IF k < 5000 THEN PRINT k   ELSE PRINT "5000 has been reached!" END IF NEXT END

The program counts from 1 to 6000. When the number 5000 is reached, you get a message in the terminal window.

You have to be aware of the right outline, otherwise it wont work.

Here is another example using the toggle button: It shows a message without a messagebox and the message can be copied into the clipboard. You need a toggle button and a textarea to get it going. You should change the property of the textarea to
 * Visible = false

When you click the button then the text will appear. When you click once again, the text will disappear.

PUBLIC SUB ToggleButton1_Click DIM Help AS String IF TextArea1.Visible = FALSE THEN ToggleButton1.Text = "Close Info " Help = "Hello, this is a info" & Chr(13) & Chr(10) Help = Help & "www.madeveryeasy.de" & Chr(13) & Chr(10) Help = Help & "rho55@gmx.de" TextArea1.Visible = TRUE TextArea1.text = Help ELSE TextArea1.Visible = FALSE ToggleButton1.Text = "Show Info" ENDIF END

Select Case
If you want to branch and you have more than 2 possible answers, then you can use the select-case command. Try this little example to get used to it. You just need an empty form to get it going. The output will be done in the terminal window.

PUBLIC SUB Form_Open PRINT Now PRINT WeekDay(Now) SELECT CASE WeekDay(Now) CASE 1 PRINT "Monday" CASE 2 PRINT "Tuesday" CASE 3 PRINT "Wednesday" CASE 4 PRINT "Thursday" CASE 5 PRINT "Friday" CASE 6 PRINT "Saturday" CASE 7 PRINT "Sunday" END SELECT END