![]() ![]() | ||
Although we've added two controls to our program, a button and a text box, they don't actually do anything when the program runs. We want to display a message when the user clicks the button, so double-click the button now to open the form's code designer to this Sub procedure:
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click End Sub
This is the event handler for the button's Click event, and it's called when the button is clicked. This Sub procedure is passed the object that caused the event (the button object itself) and an EventArgs object that has more information about the event. Note also the Handles Button1.Click part at the end, which indicates that this Sub procedure handles the Click event of Button1. In VB6, event handlers such as this could have different numbers of arguments depending on the event, but in VB .NET, event handlers are written to take two—and only two—arguments. To place text in TextBox1 when the button is clicked, all we have to do is to add this code:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = "Welcome to Visual Basic"
End Sub
Now you can run the application, as you see in Figure 4.4; when you click the button, the message appears in the text box, as you also see in that figure.
In this way, you can add code to an object's default event handler. To add code to a different event handler, select the object in the left-hand drop-down list box in a code designer, and select the event you want to add code to in the right-hand drop-down list box. Visual Basic will add an event handler for that event.
Windows user interface programming is event-driven in general; rather than long blocks of code executing by themselves, you normally place your code in event-handling procedures that react to the user's actions. Forms support many events (as you see in Table 4.3), such as the Load event, which occurs when the form is first loaded and about to be displayed. This is where you can place initialization code to customize the form when it loads (such as displaying other forms you want to make visible when the program starts). Controls support many events as well, as we'll see in the upcoming chapters.
Figure 4.4 shows how this Windows form appears—now let's take it apart in code, piece by piece.
![]() ![]() | ||