Training
Certifications
Books
Special Offers
Community




 
Microsoft® ASP.NET Web Matrix Starter Kit
Author Mike Pope
Pages 400
Disk 1 Companion CD(s)
Level Beg/Int
Published 01/22/2003
ISBN 9780735618565
Price $29.99
To see this book's discounted price, select a reseller below.
 

More Information

About the Book
Table of Contents
Sample Chapter
Index
Related Series
About the Author

Support: Book & CD

Rate this book
Barnes Noble Amazon Quantum Books

 


Chapter 5: Creating a Simple Slideshow



5   Creating a Simple Slideshow

In this chapter, you'll create a Web page that displays photos and allows users to click Previous and Next buttons to navigate between them—in 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 Works

To 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:

  • It will contain a list of the pictures you want to display. The list will be hard-coded into the page. In Chapter 12, I'll show you another, more flexible way to establish what pictures to show.
  • It will allow users to click Next and Previous buttons to move back and forth between the slides.
  • It will keep track of the current slide. As you create this feature of the slideshow program, you'll learn how to work with state management.
  • It will automatically redisplay the first slide after you've seen the last slide—that is, it will "wrap around."

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 timer—it'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 Page

The 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.

Click to view graphic
Click to view graphic

Figure 5-1   The slideshow page when it's running.

Create the page and add controls

  1. In Web Matrix, from the File menu choose New and create a new ASP.NET page named SlideShow1.aspx.
  2. Type in a heading for the page such as My Vacation Slides, and style it as Heading 1.
  3. From the Web Controls tab of the Toolbox, drag the following controls onto the page and set their properties as indicated.
  4. ControlProperty Settings
    LinkButtonID: buttonPrevious
    Text: Previous
    LinkButtonID: buttonNext
    Text: Next
    ImageID: imageSlide

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 List

In 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
Dim slideNames(5) As String
Dim currentSlide as Integer

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 values—in this case, multiple strings. The digit 5 tells Microsoft Visual Basic .NET that you'll keep up to 6 values in the array—that 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 Page

Declaring 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 back—that 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()
    path = "images/"
    slideNames(0) = "Mexico_church1.jpg"
    slideNames(1) = "Mexico_church2.jpg"
    slideNames(2) = "Mexico_church4.jpg"
    slideNames(3) = "Mexico_convent.jpg"
    slideNames(4) = "Mexico_street1.jpg"
    slideNames(5) = "Mexico_street5.jpg"
    imageSlide.ImageUrl = path & slideNames(0)
End Sub

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:

  • You would use the names of your own graphics files, of course; the files used in this code are from slides of a vacation I took in Mexico.
  • The number of elements in the slidesNames array must match the number of elements to which you dimensioned the array in the previous section. If you dimensioned the array to 6, for example, you need to be sure you have a picture for each element from 0 through 5.

Testing the Page

You'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, great—go 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 get the error message "The specified port number is already in use. Please specify a different port number," you'll know that the Web Matrix server is already running. In the notification area of the Windows taskbar, right-click the Web Matrix server icon and choose Stop, and then try running the page again.
  • Make sure the value of the path variable has a trailing forward slash (/) in it.
  • Double-check that the path variable points to the right folder.
  • Double-check the file names of your pictures, especially the extensions.
  • Don't forget to include the End Sub statement at the end of the Page_Load handler.
  • Don't forget that the counting of array elements begins at 0.

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 Navigation

The 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 Viewstate

In Chapter 1, I talked about state—the 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 again—from 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 controls—their 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:

  • The first time the page runs, you display slide 1. Your current slide number, therefore, is 0. Store that slide number in the Viewstate object, and display that slide.
  • The next time the page runs, and every time thereafter, you need to get the current slide number out of the Viewstate object. That way you'll know what slide is currently being displayed.

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()
    slideNames(0) = "Mexico_church1.jpg"
    slideNames(1) = "Mexico_church2.jpg"
    slideNames(2) = "Mexico_church4.jpg"
    slideNames(3) = "Mexico_convent.jpg"
    slideNames(4) = "Mexico_street1.jpg"
    slideNames(5) = "Mexico_street5.jpg"

    If IsPostBack = True Then
         currentSlide = Viewstate("currentSlide")
    Else
        currentSlide = 0
        Viewstate("currentSlide") = currentSlide
        imageSlide.ImageUrl = path & slideNames(currentSlide)
    End If

End Sub

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 trip—in 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 runs—if the IsPostBack property is not True—the 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 Buttons

Users 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

  1. In Design view, double-click the Next button to create a Click handler.
  2. 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" 
        runat="server">Next</asp:LinkButton>

  3. Add the following boldfaced code to the event handler:
  4. Sub buttonNext_Click(sender As Object, e As EventArgs)
        currentSlide += 1
        imageSlide.ImageUrl = path & slideNames(currentSlide)
        Viewstate("currentSlide") = currentSlide

    End Sub

    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 value—this value is initialized in the Page_Load handler before this code runs.

  5. Test this page by pressing F5. Click the Next button a few times.
  6. 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)
    currentSlide += 1
    If currentSlide > slideNames.Length - 1 Then
       currentSlide = 0
    End If
    imageSlide.ImageUrl = path & slideNames(currentSlide)
    Viewstate("currentSlide") = currentSlide
End Sub

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 speak—instead 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

  1. In Design view, double-click the Previous button to create the skeleton handler and add the HTML attribute to the control.
  2. In Code view, add the following boldfaced lines into the handler:
  3. Sub buttonPrevious_Click(sender As Object, e As EventArgs)
        currentSlide -= 1
        If currentSlide < 0 Then
           currentSlide = slideNames.Length - 1
        End If
        imageSlide.ImageUrl = path & slideNames(currentSlide)
        Viewstate("currentSlide") = currentSlide

    End Sub

    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:

  1. The first time the page runs, IsPostBack is false, so the current slide is 0. The Image control shows the slide in position 0 of the slideNames array. The current slide number, 0, is stored in Viewstate.
  2. When you click the Next button, the page runs again from scratch. This time, the IsPostBack property is true, so the program reads Viewstate to get the current slide number, which is still 0.
  3. In the Click handler for the Next button, the slide number is incremented. The slide number is now 1. The Image control displays the slide in position 1 of the array. The new slide number, 1, is stored in Viewstate.
  4. Click Next again. The Page_Load handler gets the slide number (1) out of Viewstate. The Next button's Click handler increments the slide number to 2, displays the slide, and stores the slide number.
  5. Click Previous. The Page_Load handler gets the slide number (now 2). The Previous button Click handler decrements the slide number to 1. The Image control shows the slide at position 1 in the array.
  6. And so on.

Adding a Navigation Bar

Given 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.

Click to view graphic
Click to view graphic

Figure 5-2   A navigation bar added to the slideshow page.

Configure controls for the navigation bar

  1. Change the Text property of the Previous button to < and of the Next button to >. If you want, you can change the Font and ForeColor properties to make the text more visible.
  2. To get the counter, drag a Label control between the Previous and Next buttons. (You might need to add a few spaces between the two buttons first to make room.) If necessary, set the control's background color to match the page.
  3. Resize the Label control to display all the label content. Set the Label control's ID property to labelNavbar and clear its Text property.

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

  1. In Code view, go to the Page_Load handler and add the boldfaced code shown here:
  2. Sub Page_Load()
        
        If IsPostBack = True Then
             currentSlide = Viewstate("currentSlide")
        Else
            currentSlide = 0
            Viewstate("currentSlide") = currentSlide
            imageSlide.ImageUrl = path & slideNames(currentSlide)
            labelNavbar.Text = "Slide " & currentSlide+1 & _
               " of " & slideNames.Length
        
    End If
    End Sub

  3. Go to the buttonNext_Click handler and add the same boldfaced code, as shown here:
  4. Sub buttonNext_Click(sender As Object, e As EventArgs)
        
        imageSlide.ImageUrl = path & slideNames(currentSlide)
        Viewstate("currentSlide") = currentSlide
        labelNavbar.Text = "Slide " & currentSlide+1 & " of " & _
            slideNames.Length

    End Sub

  5. Finally, go to the buttonPrevious_Click handler and add the same boldfaced code again, as shown here:
  6. Sub buttonPrevious_Click(sender As Object, e As EventArgs)
        
        imageSlide.ImageUrl = path & slideNames(currentSlide)
        Viewstate("currentSlide") = currentSlide
        labelNavbar.Text = "Slide " & currentSlide+1 & " of " & _
            slideNames.Length

    End Sub

  7. Test the slideshow by pressing F5.

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 Slideshow

You'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.

Click to view graphic
Click to view graphic

Figure 5-3   The slideshow with captions.

Add a Label control for captions

  1. Add another Label control to the page and put it below the navigation bar.
  2. Set the Label control's ID property to labelCaption and clear its Text property. If you want, you can change the Font and ForeColor properties to make the text more visible.

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

  1. In Code view, go to the top of the page and add a statement to declare an array named captions to hold the captions. This array should be the same dimension as the slideNames array. The boldfaced line in the following code shows where the declaration appears.
  2. Dim path As String = "images/"
    Dim slideNames(5) As String
    Dim captions(5) As String
    Dim currentSlide As Integer

  3. In the Page_Load handler, add statements to assign individual caption text to each element in the captions array, as shown in the boldfaced lines below. Obviously, you can add your own text.
  4. (Code Unavailable)

    Sub Page_Load()
        path = "images/"
        slideNames(0) = "Mexico_church1.jpg"
        slideNames(1) = "Mexico_church2.jpg"
        slideNames(2) = "Mexico_church4.jpg"
        slideNames(3) = "Mexico_convent.jpg"
        slideNames(4) = "Mexico_street1.jpg"
        slideNames(5) = "Mexico_street5.jpg"

        captions(0) = "Santo Domingo church"
        captions(1) = "The bell tower"
        captions(2) = "Another view of the bell tower"
        captions(3) = "Interior of convent"
        captions(4) = "Typical architecture"
        captions(5) = "Local resident"



    End Sub

  5. To display the current caption in the labelCaption control, add the following line after the code that sets the text of the labelNavbar control:
  6. 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)
        currentSlide += 1
        If currentSlide > slideNames.Length -1  Then
           currentSlide = 0
        End If
        imageSlide.ImageUrl = path & slideNames(currentSlide)
        Viewstate("currentSlide") = currentSlide
        labelNavbar.Text = "Slide " & currentSlide+1 & " of " _
           & slideNames.Length
        labelCaption.Text = captions(currentSlide)
    End Sub

  7. Make the same insertion in the Page_Load and the buttonPrevious_Click handlers.
  8. Test the page again by pressing F5. This time, you'll see captions displayed for each picture.

Looking Ahead

In 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.



Last Updated: January 4, 2003
Top of Page