|
Chapter 5: Creating a Simple Slideshow
5 Creating a Simple SlideshowIn this chapter, you'll create a Web page that displays photos and allows users to click Previous and Next buttons to navigate between themin other words, you'll create a slideshow page. Creating the slideshow page will allow you to apply the basic Web programming skills that you learned in Chapter 4. You'll learn how to store a list of pictures in the page. You'll also be introduced to the first of several techniques for storing information between round trips of the page.
How the Slideshow WorksTo give you an overview of the slideshow program you'll be creating with Web Matrix, I'll explain what the slideshow will contain and what functions it will accomplish:
Once you've gotten the basic slideshow working, you'll create a fancier navigation bar that tells users what slide they're on (slide 2 of 6, for example). You'll also add captions to the slides. Incidentally, the slideshow won't have a timerit's strictly manual navigation. Your page will use manual navigation because you can't directly create a timer in server-based code. A timer requires that a program be running to count down the seconds. But remember that on the server, the page disappears as soon as it's been sent to the browser, along with its code. So no code is left to perform the timer countdown. If you want a timer on the page, you need to code it in client script and run it in the browser. Because we're primarily focused on server code in this chapter, we won't address how to code the timer here.
Got Pictures?To create a slideshow, you'll need some pictures. For this particular page, you need to have all the pictures for your slideshow in one folder. Beneath your Web page folder, create a folder named images to hold the pictures. It's important that the folder resides underneath the folder in which you keep your Web pages. For example, if you keep your Web pages in C:\WebMatrix, the images will be in C:\WebMatrix\images.Begin by finding some Web-friendly graphics in .jpg, .gif, or .png format and copying them to the new folder that you created. Try to find images that are small enough that when they're displayed in your browser, you can see the whole picture. If you don't have any images to use for this Web page, you can use the sample images I've provided on the companion CD in the folder Webtrix\images. You'll need just five or six images. Make a note of the folder and the file names for the pictures you selected; you'll need that information later.
Creating the PageThe page you'll create isn't complex; it consists of just two LinkButton controls and an Image control. Figure 5-1 shows a picture of the slideshow page you're going to create.Figure 5-1 The slideshow page when it's running. Create the page and add controls
I'm deliberately not telling you to set the Height and Width properties for the Image control. As with the HTML <img> element, if you set the size of the Image control, all the images it displays are crammed or stretched to fit into the control's dimensions. If you do want all the images to occupy the same space, however, set the Image control's Height and Width properties. You can also decorate your page a little with colors and fonts. As an example, in HTML view, you can set the page's background color to dark blue by adding a bgcolor attribute with the value of darkblue to the <body> tag:
<body bgcolor="darkblue"> To give the buttons a contrasting look, in Design view select the Previous and Next buttons, and in the Properties window, set their ForeColor property to white. Next open the Font node in the Properties window and set the Name subproperty to Verdana and the Size subproperty to X-Small. I don't mean to belabor the details. The point is that you can set all the appearance properties by selecting the controls and using the Properties window. After you've designed the page the way you like, the next step is to build the slide list.
Building the Slide ListIn this section, I'll show you one way to hard-code the list of slides into the page. First you need to declare several variables by switching to Code view and typing in the following code at the top of the page:
Dim path As String Here you declare three variables, path, slideNames, and currentSlide. The path variable is declared to contain a string (that is, a string of characters). The currentSlide variable will contain a simple numeric value (an integer). That value will change as the page runs. The slideNames variable is an array that can contain multiple valuesin this case, multiple strings. The digit 5 tells Microsoft Visual Basic .NET that you'll keep up to 6 values in the arraythat is, the array is dimensioned to 6. Why 5 when we mean 6? Remember that when you count items in the .NET Framework, you always need to start at 0. Notice that the variables are declared at the top of the program outside of any subroutine or function on the page. They are therefore global variables, available to any subroutine or function on the page. So, the scope of the variables isn't a single subroutine, but rather is the entire page. You can set the values of the variables in one routine and then read or change their values in another routine. In contrast, any variables that you declare inside a subroutine or function are local variables, available only within that routine. They exist only as long as the routine is executing. You'll see examples of local variables later in the book.
Loading the Slide List and Initializing the PageDeclaring the variables is the preliminary part of the page programming. What you need to do now is define what happens when the page actually runs. You need to accomplish two basic tasks to initialize the slideshow: loading the slide array with the names of the slides to display and setting the Image control's ImageUrl property to point to one of your graphics files. If you don't set the ImageUrl property, naturally, no image will be displayed in the page.Remember that the page will run from scratch every time it's posted backthat is, every time the user clicks a button on the page. Therefore, you'll need to perform these two tasks every time the page runs. The logical place to perform these tasks is in the handler for the Page_Load event, which is raised every time the page makes a round trip. To build a hard-coded list of slides, in Code view create a handler for the Page_Load event by typing code such as the following below the variable declarations:
Sub Page_Load() The code assigns a different slide to each element of the array, using the array element numbers 0 through 5. After the array is filled, the program sets the ImageUrl property to the first slide. The full name of each slide consists of the path plus the name of the individual slide. So the program concatenates the values of the path variable and the first element in the imageSlide array using the & operator. Your code can differ from my example code in the following ways:
Testing the PageYou've now got a slideshow page with all the controls you need and the code that will display a picture. Before we continue with more coding, you'll want to test the page to see if what you've done up to now is working.Press F5 to run the page. After the Web server starts up, the browser should open and you should see your page with the first image on it. If so, greatgo on to the next section. If not, let's troubleshoot. If you used my example code, make sure you've copied the code as shown in the previous section. Some potential issues that might come up include the following:
If you see an error message, which is a white page with a yellow box and some red text, study it and see whether you can deduce what the problem is. At this stage, any errors you see are probably the result of typos.
Adding Slide NavigationThe interesting part of the slideshow is navigation. When you put controls on the page, you added Next and Previous buttons. Now you need to add Click event handlers to these navigation buttons to move backward and forward in the page. Before you add code that will let users navigate, however, you need a way for the page to know what slide it's on.
Maintaining the Slide Number in ViewstateIn Chapter 1, I talked about statethe fact that by default the Web server (and by extension, ASP.NET) doesn't remember any information about your page once it's been rendered. Let's look at the state issue in the slideshow example. Imagine that you start the slideshow; ASP.NET runs your page and sends it to the browser. You click the Next button, which causes the page to run againfrom scratch. The page declares the variables again and loads the array with the list of slides, just as it did the first time. It thinks you're on slide 0 again.Naturally, the people who developed ASP.NET were well aware of this problem and provided various ways to work around it. You need to figure out what slide you're on and then store the current slide number so that when the page makes a round trip, you can retrieve the number and use it. You can store the slide number and keep it in the page itself by taking advantage of a feature of ASP.NET Web pages named viewstate. Speaking broadly, viewstate is a repository in the page where the page keeps information it needs during the next round trip. Normally, the page uses viewstate to store the current property values of controlstheir text, color, and so on. However, you can store your own values in viewstate as well. When the page is posted back to the server, you can get your values back out of viewstate. The net effect is that you're storing information you need to preserve between round trips. From the programming perspective, you work with viewstate using the Viewstate object. The Viewstate object is similar to an array in that it can contain multiple objects. However, rather than maintain the object values as an ordered list that you access using an index value, the Viewstate object stores values by name.
The logic you'll need for storing a slide number in viewstate is this:
In the section "Programming the Next and Previous Buttons" later in this chapter, I'll explain how the navigation buttons use the slide number to move forward or backward in the list of slides. Now let's look at how to maintain a slide number in viewstate. In the Page_Load handler you created in the previous section, replace the line
imageSlide.ImageUrl = path & slideNames(0) with the following boldfaced code:
Sub Page_Load() The new block of code checks whether this is the first time the page has run by testing the value of the page's IsPostBack property. The value of this property is True if this is a round tripin other words, if this isn't the first time the page has been run. (A little confusing, admittedly, because our true-false test ends up being backward.) If the value of the IsPostBack property is True, the program gets the value back out of Viewstate and puts it into the currentSlide variable. If this is the first time the page runsif the IsPostBack property is not Truethe program initializes the variable currentSlide to 0 and then stores that value in Viewstate under the name currentSlide. (Viewstate values don't have to have the same name as the variables they store; but if they do, their names will be easier to remember.) The program then sets the Image control's ImageUrl property to the name of the slide at position 0 in the array. If this logic isn't perfectly clear to you right now, don't worry. For one thing, you haven't finished the page, so the examining of what's in the Viewstate object is hypothetical right now. That aside, it takes some practice to get used to working with IsPostBack and Viewstate. For now, go ahead and type in the boldfaced code that you see in this section and follow along.
Programming the Next and Previous ButtonsUsers will move back and forth in your slideshow by clicking the Next and Previous buttons. When they click the Next button, for example, the page will be posted back to the server. What you need to do, therefore, is to create Click handlers for the buttons and add the logic to navigate to the appropriate slide.Create navigation for the Next button
Web Matrix switches to Code view and creates the skeleton handler. It also adds the following attribute to the HTML syntax of the Next button:
<asp:LinkButton id="buttonNext" onclick="buttonNext_Click"
Sub buttonNext_Click(sender As Object, e As EventArgs) This code increments the value of the currentSlide variable by one. Using the new value of currentSlide, the program gets the name of the next slide out of the array and assigns it as the ImageUrl property of the Image control. Then it stores the updated value of currentSlide in Viewstate again. The code in the Click handler will run after the Page_Load handler has run. That's why you can just increment the currentSlide valuethis value is initialized in the Page_Load handler before this code runs.
It works, right?
The program has a problem, though, which you might either deduce from the code or experience firsthand when the browser displays an error. Each time you click Next, it increments the value of currentSlide and then gets the corresponding slide name from the array. Click Next enough times and currentSlide will be incremented to a value higher than the highest number of values in the slideNames array. If slideNames is dimensioned to 6, when currentSlide tries to get element 7 of the array, boom! Instead of seeing a slide in the page, you'll get an error message. To avoid the error, add to the event handler the following boldfaced code. This code causes the value of the currentSlide variable to "wrap round" to the beginning of the array when it reaches the end of the array:
Sub buttonNext_Click(sender As Object, e As EventArgs) After incrementing the value of currentSlide, the program checks the value against the highest index value in the array. All arrays have a property named Length that tells you how many elements are in the array. If you want to know the highest index value in the array, you get the array's Length property and subtract 1. For example, if an array has six elements, the highest index value is 5. If the currentSlide value is greater than the highest index value, the program just resets the value to 0. The Click handler for the Previous button is very similar to that of the Next button, except that the wraparound logic is reversed, so to speakinstead of resetting the array's index value to 0 when you reach the end of the array, you set the index value to highest index value when you reach the beginning of the array. Create navigation for the Previous button
Sub buttonPrevious_Click(sender As Object, e As EventArgs) This code decrements the value of the currentSlide variable by 1. Using the new value of currentSlide, it gets the name of the previous slide out of the array and assigns it as the ImageUrl property of the Image control. Then, it stores the updated value of currentSlide in Viewstate again. After decrementing the value of currentSlide, the program checks the value against the lowest index value in the array. If that value is less than the lowest index value, the program just resets the value to the highest index value in the array.
You might go back and look at the code for the Page_Load handler. Hopefully the If-Then-Else block with IsPostBack will make sense now. The following is a mental walkthrough of what happens as the page runs:
And so on.
Adding a Navigation BarGiven the information already in the page, it's easy to make a fancier navigation bar that consists of more than just two buttons. The navigation bar lets you navigate forward or backward to view the slides and has a counter to display the information about the current slide, as shown in Figure 5-2.Figure 5-2 A navigation bar added to the slideshow page. Configure controls for the navigation bar
To display information about the current slide, you need to change the text of the Label control each time you click a navigation button. You need this line of code to perform this task:
labelNavbar.Text = "Slide " & currentSlide+1 & " of " & slideNames.Length This code builds up a string out of the fixed text plus the current slide number plus the length of the array. We're adding 1 to the current slide number because the slide numbers start at 0, and that would look odd to users. Once the string has been built up, it's assigned to the Text property of the Label control. The following procedure describes how to update the navigation bar label text. Update the navigation bar label text
Sub Page_Load()
Sub buttonNext_Click(sender As Object, e As EventArgs)
Sub buttonPrevious_Click(sender As Object, e As EventArgs)
As you click the Next and Previous buttons, you'll see updated text. (Remember that if you didn't close the browser the last time you tested the slideshow page, you'll need to refresh in order to update the page.)
Adding Captions to the SlideshowYou'll probably want to add some captions to the slides on your Web page. No problem. A handy way to add the captions is to use a second array to store the caption text and a Label control to display the caption text. Each element of the caption array corresponds to a name in the slideNames array. When you get the slide name, you can also get the corresponding caption, as shown in Figure 5-3.Figure 5-3 The slideshow with captions. Add a Label control for captions
You need to add code to the page to create an array to hold the captions. The code is fairly easy, because it's so similar to the array you created for the slides. Add code to display captions
Dim path As String = "images/"
(Code Unavailable)
Sub Page_Load()
labelCaption.Text = captions(currentSlide) The following code shows the buttonNext_Click handler with the code inserted:
Sub buttonNext_Click(sender As Object, e As EventArgs)
Looking AheadIn this chapter, you created a Web page that was much more useful (and fun) than the simple example page you created in Chapter 4. The slideshow page from this chapter gave you a good grounding in how to add controls to the page and how to write code for them. This chapter also introduced some basic programming techniques, such as working with arrays, that you'll use frequently when programming Web pages. You also learned to use viewstate to store information between round trips of the page.In Chapter 6, you'll create a page that complements the slideshow by allowing users to set some options for how to display the slides. In the new page, you'll explore controls in more depth, and you'll also learn another handy technique for saving information between round trips: cookies.
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||