- By Michael Halvorson
Writing the Visual Basic Code
Now you’re ready to write the code for the My Web List program. Because most of the objects you’ve created already “know” how to work when the program runs, they’re ready to receive input from the user and process it. The inherent functionality of objects is one of the great strengths of Visual Studio and Visual Basic—after XAML objects are placed on a page and their properties are set, they’re ready to run. However, the core of the My Web List program—the code that starts the web browser and copies each web site that is visited to a text box—is still missing. This computing logic can only be built into the application by using program statements—code that clearly spells out what the program should do at each step of the way. Because the Visit Web Site button drives the program, you’ll create an event handler that runs, or fires, when the user clicks this button. The event handler will be created using Visual Basic code in a file that is connected to the page you just built.
In the following steps, you’ll create an event handler for a button click event using the Code Editor.
Use the Code Editor to create an event handler
In the Designer window, click the button object.
Open the Properties window, and next to the Name property text box, click the Event Handlers button (a square button displaying a lightning bolt icon).
A long list of events that the button object can detect fills the Properties window. Typical events that a button object might respond to include Click (a mouse click), DoubleClick (two mouse clicks in quick succession), DragOver (an object being dragged over a button), and Drop (an object being dragged over and dropped on a button). Since Visual Basic is at its core an event-driven programming language, much of what you do as a software developer is create user interfaces that respond to various types of input from the user, and then you write event handlers that manage the input.
Most of the time, you will only need to write event handlers for a few events associated with the objects in your programs. (The list of events is quite comprehensive, however, to give you many options.)
To create an event handler for a particular event, you double-click the text box next to the event in the Properties window. Since you want to load a webpage each time that the user clicks the button in your program, you’ll write an event handler for the button’s Click event.
Double-click the text box next to the Click event in the Properties window.
Visual Studio inserts an event handler named Button_Click_1 in the Click text box, and opens the MainPage.xaml.vb code-behind file in the Code Editor. Your screen should look like this:
Inside the Code Editor are program statements associated with the MainPage template that you opened when you started this project. This is Visual Basic program code, and you may notice right away that some of the code is organized into concise units, known as procedures. There is a procedure called OnNavigatedTo, and there is a new event handler procedure that you just created called Button_Click_1.
The Sub and End Sub keywords designate a procedure, and the keywords Protected and Private indicate how the procedure will be used. You’ll learn more about these keywords later.
When you double-clicked the Click text box in the Properties window, Visual Studio automatically added the first and last lines of the Button_Click_1 event procedure, as the following code shows:
Private Sub Button_Click_1(sender As Object, e As RoutedEventArgs) End Sub
The body of a procedure fits between these lines and is executed whenever a user activates the interface element associated with the procedure. In this case, the event is a mouse click, but as you’ll see later in the book, it could also be a different type of event. Programmers refer to this sequence as “triggering an event.”
Type the following program code and press the Enter key after the last line:
WebView1.Navigate(New Uri(NewURL.Text)) AllSites.Text = AllSites.Text & NewURL.Text & vbCrLf
As you enter the program code, Visual Studio formats the text and displays different parts of the code in color to help you identify the various elements. When you begin to type the name of an object property, Visual Basic also displays the available properties for the object you’re using in a list box, so you can double-click the property or keep typing to enter it yourself.
Your screen should now look like this:
If Visual Basic displays an additional error message, you might have misspelled a program statement. Check the offending line against the text in this book, make the necessary correction, and continue typing. (You can also delete a line and type it again from scratch.)
Program statements are a little like complete sentences in a human language—statements can be of varying lengths but must follow the grammatical rules of the language. In Visual Studio, program statements can be composed of keywords, properties, object names, variables, numbers, special symbols, and other values. As you enter these items in the Code Editor, Visual Studio uses a feature known as IntelliSense to help you write the code. With IntelliSense, as Visual Studio recognizes language elements, it will automatically complete many expressions.
Click the Save All command on the File menu to save your additions to the program.
The Save All command saves everything in your project—the project file, the pages, the code-behind files, the assets, the package manifest, and other related components in your application. Since this is the first time that you have saved your project, the Save Project dialog box opens, prompting you for the name and location of the project. (If your copy of Visual Studio is configured to prompt you for a location when you first create your project, you won’t see the Save Project dialog box now—Visual Studio just saves your changes.)
Browse and select a location for your files.
I recommend that you use the My Documents\Start Here! Programming in Visual Basic\Chapter 02 folder (the location of the book’s sample files), but the location is up to you. Since you used the “My” prefix when you originally opened your project, this version won’t overwrite the practice file that I built for you on disk.
Clear the Create Directory For Solution check box.
When this check box is selected, it creates a second folder for your program’s solution files, which is not necessary for solutions that contain only one project (the situation for most programs in this book).
Click Save to save your files.
Notice that the object names in the Code Editor (WebView1, NewURL, and AllSites) are now displayed in normal type.
A Look at the Visual Basic Code-Behind File
The Button_Click_1 event handler is executed when the user clicks the Visit Web Site button on the page. The procedure uses some interesting Visual Basic code, which is worth looking at before moving on.
The first statement uses the Navigate method of the WebView1 object to load a webpage into the window you created earlier in this project:
Navigate is a method, or a statement that performs a specific action for an object in your program. The web view object has numerous methods, but the Navigate method is the one that prompts web view to load a webpage. Right now, you should notice that the Navigate method is connected to the WebView1 object by a period (.), which is the same syntax that is used to reference a property in program code.
In parentheses following the Navigate method is a reference to the text that the user has entered into the first text box on the page (NewURL). The text is stored in the Text property, and the New Uri keywords are used to put the user input into a standard format used for web addresses—the so-called uniform resource indicator (URI) format. Since this is a simple demonstration program, I am assuming that the user is entering the web address in the proper way. In fact, if an incorrect or badly formatted web address is entered, the program will not load the webpage and there will be little indication that something went wrong. This is not what you would do in a commercial application, of course, and I’ll show you later in the book how to be much more deliberate about handling errors introduced by the user.
The second statement builds the list of web sites that the user visits while the program runs:
AllSites.Text = AllSites.Text & NewURL.Text & vbCrLf
Each web site is entered through the Text property of the NewURL object. This Text property is combined with the current contents of the AllSites text box through the string-concatenation operator (&), which appends each new web site that is entered to the bottom of the list. A line break is added to the end of each line by the vbCrLf constant. You’ll learn more about the string-concatenation operator when you learn about how Visual Basic computes mathematical and textual operations in Chapter 6.
With just two lines of Visual Basic code, your program is complete. Now you are ready to run the application.