Sequential execution in multi-line event handlers

To this point, we have defined user interfaces and coded event handlers; however, our event handlers have been very simple. If you look back at them, each was only one instruction long. But, event handlers can have many instructions, and they are executed in order from top to bottom, one at a time. We will refer to this as sequential execution since the instructions are executed in sequence.

In subsequent notes we will how to break this sequential flow of control using conditional statements, looping and recursion).

Consider this program that displays several lines. When you run it, you see that it displays five lines in the TextBox, not just one as in our earlier example. The event handler that executes when the user clicks the "Display the greeting" button has six statements, one to clear the TextBox and five to display the greeting lines:

Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
   txtGreet.Clear()
   txtGreet.AppendText("Hello my friend!" & vbCrLf)
   txtGreet.AppendText("You are looking good." & vbCrLf)
   txtGreet.AppendText("Are you married?" & vbCrLf)
   txtGreet.AppendText("What is your phone number?" & vbCrLf)
   txtGreet.AppendText("Goodbye my friend!")
End Sub

When the program executes, the message seems to appear all at once, but the speed of the computer has deceived you. In fact, the instructions execute in sequence, one at a time. The computer does not go on to the next instruction until the one it is working on is complete. You can see this if you run the message display program with a delay.

When your programs do not do what you wish them to, you will often be able to discover the bug by pretending to be the computer and slowly stepping through the instruction in order in your mind.

Finally, note that both the event handler listed above and the Clear the Screen event handler:

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
   txtGreet.Clear()
End Sub

use the Clear method of the TextBox.


Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.