Beginning Visual Basic 2005 (2006)
.pdf
Chapter 6
Figure 6-4
Since you selected btnSayHello in the Class Name combo box, the Method Name combo box now contains items that are exclusively rated to that control. In this case, you have a huge list of events. One of those events, Click, is shown in bold because you provided a definition for that event. If you select Click, you’ll be taken to the method in Form1 that provides an event handler for this method.
8.Now add another event handler to the Button control. With btnSayHello still selected in the Class Name combo box, select the MouseEnter event in the Method Name combo box. A new event handler method will be created, and you need to add the following code to it as highlighted:
Private Sub btnSayHello_MouseEnter(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnSayHello.MouseEnter
‘Change the Button text
btnSayHello.Text = “The mouse is here!” End Sub
The MouseEnter event will be fired whenever the mouse pointer “enters” the control, in other words, crosses its boundary.
9.To complete this exercise, you need to add another event handler. Select btnSayHello in the Class Name combo box and select the MouseLeave event in the Method Name combo box. Again, a new event will be created, so add the highlighted code here:
176
Building Windows Applications
Private Sub btnSayHello_MouseLeave(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnSayHello.MouseLeave
‘Change the Button text
btnSayHello.Text = “The mouse has gone!” End Sub
The MouseLeave event will be fired whenever the mouse pointer moves back outside of the control.
10.Run the project. Move the mouse over and away from the control, and you’ll see the text change, as shown in Figure 6-5.
Figure 6-5
How It Works
Most of the controls that you use will have a dazzling array of events, although in day-to-day programming only a few of them will be consistently useful. For the Button control, the most useful is usually the Click event.
Visual Basic 2005 knows enough about the control to create the default event handlers for you automatically. This makes your life a lot easier and saves on typing!
When you created your MouseEnter event and added the highlighted code:
Private Sub btnSayHello_MouseEnter(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnSayHello.MouseEnter
‘Change the Button text btnSayHello.Text = “The mouse is here!”
End Sub
You’ll notice that at the end of the method definition is the Handles keyword. This ties the method definition into the btnSayHello.MouseEnter event. When the button fires this event, your code will be executed.
Although previously you changed only the button’s Text property at design time using the Properties window, here you can see that you can change it at run time too.
As a quick reminder here, design time is the term used to define the period of time that you actually writing the program, in other words, working with the Designer or adding code. Run time is the term used to define the period of time when the program is running.
177
Chapter 6
Likewise, the MouseLeave event works in a very similar way:
Private Sub btnSayHello_MouseLeave(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnSayHello.MouseLeave
‘Change the Button text btnSayHello.Text = “The mouse has gone!”
End Sub
Building a Simple Application
Visual Studio 2005 comes with a comprehensive set of controls that you can use in your projects. For the most part, you’ll be able to build all of your applications using just these controls, but in Chapter 13 you look at how you can create your own application.
Take a look at how you can use some of these controls to put together a basic application. In the following Try It Out, you build a basic Windows application that lets the user enter text into a form. The application will count the number of words and letters in the block of text that they enter.
Building the Form
The first job is to start a new project and build a form. This form will contain a multiline text box where you can enter text. It will also contain two radio buttons that will give you the option of counting either the words or the number of characters in the text box.
Try It Out |
Building the Form |
1.Select File New Project from the Visual Studio 2005 menu and create a new Windows Application project. Enter a project name of Word Counter and click OK.
2.Click on Form1 and, in the Properties window, set the Size property to 424, 312, the StartPosition property to CenterScreen, and the Text property to Word Counter.
3.Drag a TextBox control from the Toolbox and drop it on the form. Now change the properties of the text box as shown in the following list:
Set Name to txtWords.
Set Location to 8, 32.
Set Multiline to True.
Set ScrollBars to Vertical.
Set Size to 400, 217.
4.To tell the user what to do with the form, you add a label. Select the Label control from the Toolbox, drag and drop it just above the text box. Change the Text property to Enter some text into this box.
178
Building Windows Applications
Strictly speaking, unless you’re going to need to talk to the control from your code, you don’t need to change its Name property. With the text box, you need to use its properties and methods to make the application work. However, the label is just there for esthetics, so you don’t need to change the name for Label1. (This depends on how fussy you are — some developers give every control a specific name, whereas others name only specific controls that really need a name.)
It’s worth noting that if you are going to refer to a control from Visual Basic 2005 code, it’s a good coding practice to give the control a name. Developers should be able to determine what the control represents based on its name even if they’ve never seen your code before. Refer to the section on Modified Hungarian Notation in Chapter 1 for prefixes to use with your control names.
5.Your application is going to be capable of counting either the characters the user entered or the number of words. To allow the user to select the preferred count, you use two radio buttons. Draw two RadioButton controls onto the form next to each other below the text box. You need to refer to the radio buttons from your Visual Basic 2005 code, so change the properties as shown in the following lists:
For the first radio button:
Set Name to radCountChars.
Set Checked to True.
Set Text to Chars.
For the second radio button:
Set Name to radCountWords.
Set Text to Words.
6.As the user types, you’ll take the characters that the user enters and count up the words or characters as appropriate. You want to pass your results to the user, so add two new Label controls next to the RadioButton controls that you just added.
7.The first Label control (marked Label2) is just for esthetics, so change its Text property to The results are:. The second Label control will report the results, so you need to give it a name. Set the Name property as lblResults and clear the Text property.
8.You also need a Button control that will show a message box, so add a Button control to the form and align it to the bottom right of the text box. You don’t strictly need this because the user can read the results on the form, but it will illustrate a couple of important points. Change the Name property to btnShowMe and the Text property to Show Me!. Your completed form should look similar to the one shown in Figure 6-6.
9.Now that you have the controls laid out on your form the way you want it, you can make sure you keep it that way. Make sure you select one of the controls and not the actual form, and then select Format Lock Controls from the menu. This sets the Locked property of each of the controls to True and prevents them from accidentally being moved, resized, or deleted.
179
Chapter 6
Figure 6-6
Counting Characters
With your form designed, you’ll want to build some event handlers to count the number of characters in a block of text that the user types. Switch to the form’s code view by right-clicking the form in the Solution Explorer and choosing View Code from the context menu or by right-clicking the form and choosing View Code from the context menu. Since your application will be able to count words and characters, you build separate functions for each. In this Try It Out, you write the code to count characters.
Try It Out |
Counting Characters |
1.Add this code to the Form1 class. Remember, to insert an XML Document Comment block, you need to type three apostrophes above the function:
‘’’ <summary>
‘’’ Count the characters in a block of text ‘’’ </summary>
‘’’ <param name=”text”>The string containing the text to count ‘’’ characters in</param>
‘’’ <returns>The number of characters in the string</returns> ‘’’ <remarks></remarks>
Private Function CountCharacters(ByVal text As String) As Integer Return text.Length
End Function
2.Now you need to build an event handler for the text box. Select txtWords in the Class Name combo box and, in the Method Name combo box, select the TextChanged event. Add this highlighted code to the event handler:
Private Sub txtWords_TextChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles txtWords.TextChanged
180
Building Windows Applications
‘Count the number of characters
Dim intChars As Integer = CountCharacters(txtWords.Text)
‘Display the results
lblResults.Text = intChars & “ characters” End Sub
3.Run the project. Enter some text into the text box and you’ll see a screen like the one in Figure 6-7.
Figure 6-7
How It Works
Notice that whenever you type a character into the text box, the label at the bottom of the form reports the current number of characters. That’s because the TextChanged event is fired whenever the user changes the text in the box. This happens when new text is entered, when changes are made to existing text, and when old text is deleted. You are “listening” for this event, and whenever you “hear” it (or rather receive it), you call CountCharacters and pass in the block of text. As the user types text into the txtWords text box, the Text property is updated to reflect the text that has been entered. You can get the value for this property (in other words, the block of text) and pass it to CountCharacters:
‘Count the number of characters
Dim intChars As Integer = CountCharacters(txtWords.Text)
The CountCharacters function in return counts the characters and passes back an integer representing the number of characters that it has counted:
Return text.Length
After you have the number of characters, you update the lblResults control:
‘Display the results
lblResults.Text = intChars & “ characters”
181
Chapter 6
Counting Words
Although building a Visual Basic 2005 application is actually very easy, building an elegant solution to a problem requires a combination of thought and experience.
Take your application, for example. When the Words radio button is checked, you want to count the number of words, whereas when Chars is checked, you want to count the number of characters. This has three implications. First, when you respond to the TextChanged event, you need to call a different method that counts the words, rather than your existing method for counting characters. This isn’t too difficult.
Second, whenever you select a different radio button, you need to change the text in the results from “characters” to “words” or back again. In a similar way, whenever the Show Me! button is clicked, you need to take the same result, but rather than displaying it in the Label control, you need to use a message box.
Now add some more event handlers to your code, and when you finish, examine the logic behind the techniques you used.
Try It Out |
Counting Words |
1.Stop your project if it is still running. The first thing you want to do is add another function that will count the number of words in a block of text. Add this code to create the CountWords function:
‘’’ <summary>
‘’’ Count the number of words in a block of text ‘’’ </summary>
‘’’ <param name=”text”>The string containing the text to count ‘’’ words in</param>
‘’’ <returns>The number of words in the string</returns> ‘’’ <remarks></remarks>
Private Function CountWords(ByVal text As String) As Integer ‘Is the text box empty
If txtWords.Text = String.Empty Then Return 0
‘Split the words
Dim strWords() As String = text.Split(“ “)
‘Return the number of words Return strWords.Length
End Function
2.The UpdateDisplay procedure deals with the hassle of getting the text from the text box and updating the display. It also understands whether it’s supposed to find the number of words or number of characters by looking at the Checked property on the radCountWords radio button. Add this code to create the procedure:
Private Sub UpdateDisplay() ‘Do we want to count words?
If radCountWords.Checked = True Then
182
Building Windows Applications
‘Update the results
lblResults.Text = CountWords(txtWords.Text) & “ words”
Else
‘Update the results
lblResults.Text = CountCharacters(txtWords.Text) & “ characters” End If
End Sub
3.Now, instead of calling CountCharacters from within your TextChanged handler, you want to call UpdateDisplay. Make the following change:
Private Sub txtWords_TextChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles txtWords.TextChanged
‘Something changed so display the results
UpdateDisplay()
End Sub
4.Finally, you want the display to alter when you change the radio button from Chars to Words and vice versa. To add the CheckedChanged event, select radCountWords in the Class Name combo box at the top of the code window and the CheckedChanged in the Method Name combo box. Add the following highlighted code to the event handler procedure:
Private Sub radCountWords_CheckedChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles radCountWords.CheckedChanged
‘Something changed so display the results
UpdateDisplay()
End Sub
5.Repeat the previous step for the radCountChars radio button:
Private Sub radCountChars_CheckedChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles radCountChars.CheckedChanged
‘Something changed so display the results
UpdateDisplay()
End Sub
6.Run the project. Enter some text in the box and check Words. Notice how the display changes as shown in Figure 6-8.
How It Works
Before you look at the technique that you used to put the form together, take a quick look at the
CountWords function:
‘’’ <summary>
‘’’ Count the number of words in a block of text ‘’’ </summary>
‘’’ <param name=”text”>The string containing the text to count ‘’’ words in</param>
‘’’ <returns>The number of words in the string</returns> ‘’’ <remarks></remarks>
183
Chapter 6
Private Function CountWords(ByVal text As String) As Integer ‘Is the text box empty
If txtWords.Text = String.Empty Then Return 0
‘Split the words
Dim strWords() As String = text.Split(“ “)
‘Return the number of words Return strWords.Length
End Function
Figure 6-8
You start by checking to see whether the text box is empty by comparing the Text property of the text box to the Empty field of the String class. The Empty field of the String class is equivalent to a zero length string (“”); if no text has been entered, you immediately return from the function with a value of 0.
The Split method of the String class is used to take a string and turn it into an array of string objects. Here, the parameter you passed is equivalent to the “space” character, so you’re effectively telling Split to break up the string based on a space. This means that Split returns an array containing each of the words in the string. You then return the length of this array, in other words, the number of words back to the caller.
Note that because this code uses a single space character to split the text into words, you’ll get unexpected behavior if you separate your words with more than one space character or use the Return key to start a new line.
One of the golden rules of programming is that you never write more code than you absolutely have to. In particular, when you find yourself in a position where you are going to write the same piece of code twice, try to find a workaround that requires that you write it only once. In this example, you have to
184
Building Windows Applications
change the value displayed in lblResults from two different places. The most sensible way to do this is to split the code that updates the label into a separate method; UpdateDisplay. You can then easily set up the TextChanged and CheckedChanged event handlers to call this method. The upshot of this is that you only have to write the tricky “get the text, find the results, and update them” routine once. This technique also creates code that is easier to change in the future and easier to debug when a problem is found.
Private Sub UpdateDisplay() ‘Do we want to count words?
If radCountWords.Checked = True Then ‘Update the results
lblResults.Text = CountWords(txtWords.Text) & “ words”
Else
‘Update the results
lblResults.Text = CountCharacters(txtWords.Text) & “ characters” End If
End Function
You’ll find as you build applications that this technique of breaking out the code for an event handler is something you’ll do quite often.
Creating the Show Me! Button Code
To finish this exercise, you need to write code for the Show Me! button. All you’re going to do with this button is display a message box containing the same text that’s displayed on lblResults.
Try It Out |
Coding the Show Me! Button |
1.In the Code Editor, select btnShowMe from the Class Name combo box and then select the Click event in the Method Name combo box. Then add the highlighted code:
Private Sub btnShowMe_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles btnShowMe.Click
‘Display the text contained in the Label control
MessageBox.Show(lblResults.Text, “Word Counter”)
End Sub
2.Run the project and type something into the text box. Then click the Show Me! button, and the same value will be displayed in the message box appears in the results Label control.
How It Works
When you click the button, the code in the Click event is using the Text property from the Label control as the text parameter (the message) for the MessageBox.Show method:
‘Display the text contained in the Label control MessageBox.Show(lblResults.Text, “Word Counter”)
185
