Creating the Slide Details Page


The details page allows you to enter information about individual slides for a specific slideshow. Remember that a slide entry points to a graphics file in your Web application. You can create multiple slide entries for the same picture, which you would do if you wanted the same picture to appear in multiple slideshows. When the details page is running, it will look like the page in Figure 13-2.

click to expand
Figure 13-2: The details page, with several slides already entered.

The details page resembles the slideshow master page. You ll use text boxes to enter slide information such as the URL, caption, and date. The page contains an MxDataGrid control to display slides. But the details page is different from the slideshow page in the following interesting ways:

  • You ll pass the slideshow name to the details page. When you re working in the details page, you re always working with the slides for a single slideshow.

  • The MxDataGrid control displays only the slides for the current slideshow. (In the master page, the MxDataGrid control displays all the slideshows.) Because we want to show only selected slides, we ll need to do a little extra work to get the correct data for the grid.

  • You ll be able to delete individual slides using a facility of the MxDataGrid control.

  • You ll be able to edit individual slides in the MxDataGrid control. Each row of the grid will contain an Edit button. When you click the Edit button, you ll be able to change the URL, caption, or date of existing slides in the current slideshow. As with displaying selected slides, however, you ll need to add code to the page to get editing to work.

As always, I ll walk you through all the code in detail. Let s start by creating the new page.

Create the  AddSlides.aspx page

  1. In Web Matrix, create a new page named  AddSlides.aspx. You must use this name or the page name you used when you created the HyperLinkField column in the MxDataGrid control on the master page.

  2. Type in the heading Add Slides to Slideshow.

  3. Using Figure 13-2 as a guide, drag the following controls from the Web Controls tab of the Toolbox onto the page and set their properties as indicated:

    Control

    Property Settings

    Label

    ID: labelSlideshowName

    Text: (empty)

    TextBox

    ID: textSlideURL

    MaxLength: 65

    TextBox

    ID: textSlideCaption

    MaxLength: 250

    TextMode: Multiline

    TextBox

    ID: textSlideDate

    MaxLength: 50

    Button

    ID: buttonAddSlide

    Text: Add Slide

    HyperLink

    ID: linkCreateSlideshowPage

    NavigateUrl:  CreateSlideshow.aspx

    Text: Return to Slideshow master page

    Label

    ID: labelError

    Font.Bold: True

    ForeColor: Red

    Text: (empty)

  • Using Figure 13-2 as a guide, type text into the page for captions.

  • That s it for the individual controls; we ll add the MxDataGrid control in a moment. First, however, let s add code to read the slideshow name passed from the master page.

    Reading the Slideshow Name from the Master Page

    The details page is displayed when a user clicks a hyperlink in the grid on the master page. The link URL jumps to the details page and passes a query string that contains the name of the slideshow to work with. You therefore need to read the slideshow name out of the query string so that you know what slideshow you re adding slides to. As I described in Chapter 12, whenever you work with a query string in a page, you need to be sure it doesn t include malicious code query strings are easy to spoof because users can see and edit them in the Address box of their browser. So you ll also need code to check for HTML characters.

    Switch to Code view, and create a Page_Load handler that looks like the following:

    Sub Page_Load(     If Not Page.IsPostBack The         If Request.QueryString("slideshowname" ) Is Nothing The             Response.Redirect("CreateSlideshow .aspx"         Els             Dim slideshowName as Strin             slideshowName = Request.QueryStrin g("slideshowname"             If slideshowName = Server.HtmlEnco de(slideshowName) The                 labelSlideshowName.Text = slid eshowNam             Els                 labelError.Text = "Invalid slideshow name!                 slideshowName = "             End I         End I     End I End Sub

    The first task that the code performs is to test whether a query string value named slideshowname was passed to the page. If not, the code jumps back to the master page. Performing this test is useful in case a user manages to display the details page without first going to the master page.

    If the query string does contain a value named slideshowname, you use the Server.HtmlEncode method to test whether the string contains any HTML. If the query string contains HTML, the code displays an error and exits the handler. Otherwise, you set the Text property of the labelSlideshowName control to the value of the query string value. Because the page needs to read the query string and set the labelSlideshowName control s Text property only the first time the page runs, all the code in the Page_Load handler is inside a test for the page s IsPostBack property.

    Test the page by running it. The  AddSlides.aspx page won t be displayed in the browser. Instead, you ll be redirected to the  CreateSlideshow.aspx page. On the master page, click an Add/Edit Slides link in the grid, which will take you to the  AddSlides.aspx page. The slideshow name will appear in the label at the top of the page. When you re satisfied that the links work, close the browser and return to Web Matrix. Let s move on to the code that will insert new slides into the database.

    Inserting Individual Slides into the Database

    Let s review quickly the information you need for individual slides in the Slides table. The SlideID column is auto-incremented, so you don t need to provide a value for that column. Every slide in the slideshow is associated with a specific slideshow, which is the value of the SlideshowName column. The slideshow name for all the slides you enter on this page is passed in the query string. The user will supply the values for the remaining three columns in the Slides tables SlideURL, SlideCaption, and SlideDate in the text boxes on the page.

    After you ve gathered up the necessary information, you can insert a new slide into the Slides table. The technique for inserting an individual slide into the database is one you re familiar with you have Web Matrix generate some insert code for you, and you call the code with the appropriate values.

    Generate code to insert a new slide

    1. In Code view, drag an Insert Data Method element from the Toolbox onto the page. Specify the connection information for your instance of MSDE and choose the WebMatrix database, as usual.

    2. When the Query Builder opens, select the Slides table and make sure all the column names are unchecked except for SlideID, as shown here:

      click to expand

    SlideID is checked because it s an auto-increment column, so it has a default value.

  • Click Next, name the method AddSlide, and then click Finish.

  • Now you need to call this AddSlide method. Switch to Design view, and double-click the Add Slide button to create a Click handler for it. Add code to the Click handler so that the handler looks like the following:

    Sub buttonAddSlide_Click(sender As Object, e A s EventArgs     Dim slideURL as Strin     Dim  slideCaption as Strin     Dim slideDate as Strin     slideURL = Server.HtmlEncode(textSlideURL. Text     slideCaption = Server.HtmlEncode(textSlide Caption.Text     slideDate = Server.HtmlEncode(textSlideDat e.Text     Tr         AddSlide(labelSlideshowName.Text, slid eURL, slideCaption,               slideDate         textSlideURL.Text = "         textSlideCaption.Text = "         textSlideDate.Text = "     Catch ex As Exceptio         labelError.Text = "Unable to add a sli de to the slideshow.     End Tr End Sub

    This code is almost identical to the code you created earlier in this chapter to insert a new slideshow record. (This code is simpler, however.) As always, you call the Server.HtmlEncode method to sanitize user input from the text boxes before putting the text box values into the appropriate variables. When you call the AddSlide method, you pass it four values the slideshow name that you read from the labelSlideshowName control and the three values from the text boxes. The slideshow name was originally passed to the page in the query string. You call the AddSlide method inside a Try-Catch block and display an error message in the Catch block. You clear each field after the new slide is added.

    Test the page by running it. You ll be redirected to the  CreateSlideshow.aspx page. Select an existing slideshow and click Add/Edit Slides. The  AddSlides.aspx page is displayed. You ll be able to add slide information and click the Add Slide button to save a new slide in the database.

    Although you can add slides, you don t have a convenient way to see what slides you ve created for a slideshow. In the next section, you ll add functionality to the page so that it will display slides for the current slideshow.

    Displaying Slides for the Current Slideshow

    As you did with the slideshows in the master page, you ll display a list of slides in a grid in the details page. You ll accomplish this task using an MxDataGrid control, as usual. However, you want to show only the slides for the current slideshow, so you ll need to execute a SQL Select statement with a Where clause that finds the slides for the current slideshow only.

    Display current slideshow slides

    1. In Web Matrix, switch to Design view.

    2. From the Data window, drag the Slides table to the bottom of the page. Web Matrix adds a SqlDataSourceControl and an MxDataGrid control to the page.

    3. Select the MxDataGrid control, and in the Properties window, click the ellipsis in the Fields property to open the MxDataGridField Collection Editor dialog box.

    4. Under Members, remove the BoundField object for the SlideshowName column you don t need to display the slideshow name in the grid, because you already have it in the labelSlideshowName control.

    5. Select the BoundField object for the SlideID column. In the right-hand properties grid, set the object s ReadOnly property to True. You need to display the SlideID column later, when you re editing slides, but you won t want to allow people to change the ID.

    6. Click OK when you ve finished.

      Tip 

      You might want to set the AllowPaging property of the MxDataGrid control to False. That way, you ll be able to see all the slides for the current show without paging.

    7. Select the SqlDataSourceControl control on the page, and in the Properties window, modify the control s SelectCommand property by adding a Where clause. In the following command, the Where clause you should add is shown in boldface:

      SELECT * FROM [Slides] WHERE slideshowname=@slideshowname 

      You re configuring the data source control so that it returns only the records for a selected slideshow. The value @slideshowname is a parameter a placeholder for the slideshow name that will be passed to the SQL statement when the page runs. The parameter name must begin with the @ sign, a rule imposed by MSDE (and SQL Server).

    8. Switch to Code view. You need to provide a value for the @slideshowname parameter in the SQL Select command. In the Page_Load handler, add the statement shown here in boldface:

      Sub Page_Load(    If Not Page.IsPostBack The       If Request.QueryString("slideshowname")  Is Nothing The           Response.Redirect("CreateSlideshow.a spx"       Els           Dim slideshowName as Strin           slideshowName = Request.QueryString( "slideshowname"           If slideshowName = Server.HtmlEncode (slideshowName) The               labelSlideshowName.Text = slides howNam           Els               labelError.Text = "Invalid slideshow name!               slideshowName = "           End I           SqlDataSourceControl1.Parameters.Add("@slideshowname", _              slideshowName)        End I    End I End Sub
      Caution 

      Be sure to insert the new line at the correct location in the Page_Load handler; otherwise, the page won t work properly.

      The SqlDataSourceControl control supports a Parameters collection, which is a collection of values that you can pass to the SQL Select statement. In your case, you need to pass only one value namely, slideshowname. Therefore, you create only a single item for the Parameters collection. To create a parameter, you call the Add method of the Parameters collection. In the Add method call, you specify the name of the parameter in the SQL statement to fill (@slideshowname) and the value you want to pass to the parameter (the local variable slideshowName).

    9. Modify the buttonAddSlide_Click handler to call the MxDataGrid control s DataBind method after you ve added a new slide. Doing so will refresh the grid with the new slide information after a new record is added to the database. The new call is shown in boldface in the following code:

      Sub buttonAddSlide_Click(sender As Object, e A s EventArgs          Tr         AddSlide(labelSlideshowName.Text, slid eURL, slideCaption,              slideDate         MxDataGrid1.DataBind()         textSlideURL.Text = "         textSlideCaption.Text = "         textSlideDate.Text = "     Catch ex As Exceptio         labelError.Text = "Unable to add a sli de to the slideshow.     End Tr End Sub 

    You re ready now to add some slides and view the results in the grid. Run the page by pressing F5. As before, you ll be redirected to the  CreateSlideshow.aspx page. Select an existing slideshow, and click Add/ Edit Slides. The  AddSlides.aspx page is displayed. If the slideshow you selected already contains slides, the slides are displayed in the grid. Type a URL, a caption, and a date, and then click Add Slide. As soon as you click the Add Slide button, you ll see the new slide information added to the grid, as shown in Figure 13-3.

    click to expand
    Figure 13-3: Adding a new slide and displaying it in the grid.

    Deleting Existing Slides

    You can easily add the ability to delete a slide that you don t want any more. When you delete a slide, you take it out of the database so that it no longer appears in a slideshow; you don t delete the graphics file itself.

    You can enable deleting using the MxDataGrid and SqlDataSourceControl controls that you already have on the page. You ll configure the MxDataGrid control to display Delete buttons next to each slide. When you click a Delete button, the grid can then call upon the SqlDataSourceControl control to execute a SQL Delete statement that removes the slide from the database. The best part is that you don t need to write a single line of code to get deletion to work.

    Add delete capability to the MxDataGrid control

    1. In Design view of the  AddSlides.aspx page, select the MxDataGrid1 control.

    2. In the Properties window, click the ellipsis button in the Fields property. Web Matrix opens the MxDataGridField Collection Editor dialog box.

    3. Click the drop-down button next to the Add button. Web Matrix displays a list of the types of columns you can add to the grid.

    4. Choose ButtonField. Using the up and down arrow buttons next to the Members list, move the new ButtonField object to the top of the list. This causes the new button to appear left-most in the grid.

    5. Select the ButtonField object, and in the right-hand properties grid, set the button s Text property to Delete and set its CommandName property to Delete as well. The Text property specifies how the new button will appear in the grid. The CommandName property specifies the action that the grid will take when the button is clicked. The command name Delete is a predefined command in the MxDataGrid control; when the grid receives the command name Delete from a button, the grid will delete the record in that row.

    When you ve finished, the MxDataGridField Collection Editor dialog box will look like Figure 13-4.

    click to expand
    Figure 13-4: The MxDataGridField collection editor when you ve finished creating a Delete button.

    Close the collection editor, and test the page by running it again. Select a slideshow on the slideshow master page, and click the Add/Edit Slides link to display the  AddSlides.aspx page. Enter a new slide record, and when the record appears in the grid, click the Delete button next to the record to remove it again.

    You can now enter new slides and delete the slides you don t need any more. But what if you want to change a slide you ve already entered? Let s add editing capability next.

    Editing Existing Slides

    The final task you want to be able to accomplish with your slides is to edit them that is, change the URL, caption, or date for the slides you ve already created. Editing works much like deleting. You add an Edit button to the MxDataGrid control. When the button is clicked, it calls upon the SqlDataSourceControl control to perform the edit by executing a SQL Update statement. Unlike deleting, however, editing isn t completely automatic. Here s why: when you dropped the Slides table onto the page, Web Matrix added a SQL Update command to the SqlDataSourceControl control that looks something like the following (which I ve wrapped to make it easier to read):

    UPDATE [Slides] SET      [SlideshowName]=@SlideshowName     [SlideURL]=@SlideURL     [SlideCaption]=@SlideCaption     [SlideDate]=@SlideDate  WHERE [SlideID]=@SlideID

    As you can see, the Update statement has five parameters. To get editing to work, therefore, you need to pass values for those five parameters. Passing parameter values isn t too hard; you added code to pass a parameter value to the SQL Select statement earlier in this section, when you added the MxDataGrid control to the  AddSlides.aspx page. However, getting the updated slide information is a little tricky. I ll show you how now.

    Add edit capability to the MxDataGrid control

    1. In Design view, select the MxDataGrid control.

    2. In the Properties window, click the ellipsis button in the Fields property to open the MxDataGridField Collection Editor dialog box.

    3. Click the drop-down button next to the Add button, and choose EditCommandField. If you want, use the arrows keys to move the EditCommandField object up so that it appears on the left side of the grid.

    4. Select the EditCommandField object, and in the right-hand properties grid, set the following properties:

      When the grid is first displayed, the text of the button you re creating will be Edit the value of the EditText property. When you click an Edit button, the grid row will be redisplayed with text boxes for editing the slide details. In addition, the Edit button will be replaced with two buttons, one labeled Save (the value of the UpdateText property) and the other labeled Cancel (the value of the CancelText property).

    5. Close the collection editor when you ve finished setting the properties.

    6. Test the page by running it again. Select a slideshow on the slideshow master page, and click the Add/Edit Slides link to display the  AddSlides.aspx page. This time, the grid has a column of Edit buttons, as shown here:

      click to expand

    7. Click an Edit button. The row is redisplayed with the Save and Cancel buttons, and the data is displayed in editable text boxes, as shown here:

      click to expand

      Notice that the SlideID column does not contain a text box, because earlier you set that column to be read-only. We haven t finished with the Edit button, so clicking the Save button doesn t save changes yet. Click Cancel, and the row is displayed normally again.

    By adding the Edit button to the grid, you ve created the mechanism for putting a row in the MxDataGrid control into edit mode, but you still need to perform the actual update. Let s proceed to that final task next.

    Programming the Edit Buttons to Update the Database

    When a grid row is in edit mode, the editable information is displayed in text boxes, where users can make changes. To save changes, users click the Save button. To send the users changes to the database, you effectively need to create a handler for the Update button. In the handler, you get the new values that the user has entered into the text boxes and pass them to the SQL Update statement already lurking in the SqlDataSourceControl control. The process of creating a handler for the Update button, getting the edited values, and passing the values to the SQL Update statement is probably the least intuitive technique you ll use in this book, so I need to set the stage for you.

    To send users updates to the database, you first need to read the values out of the text boxes (or, for the slide ID, just out of the column, because the SlideID column contains a read-only value). However, your access to the text box values and the slideID is not very direct. When the user clicks a Save button, the MxDataGrid control is simply going to hand you the entire row out of the grid in the form of a single object of type Item. It will be up to you to drill down into the Item object. You need to parse through individual cells (columns), grab the text box control in each cell that has a text box, and then read the value (Text property) out of each TextBox control. The MxDataGrid control doesn t provide any other way to retrieve the edited values, which is unfortunate. But now that you know in outline what we need to do to accomplish the updating task, let s forge ahead. Before writing any code, you need to create a skeleton event handler where you will update the data.

    Create the event handler for updating data

    1. Select the MxDataGrid control on the  AddSlides.aspx page in Design view.

    2. In the Properties window, click the Events button on the toolbar. The Properties window displays events for the MxDataGrid control.

    3. Double-click in the text box for the BeforeUpdate event. Web Matrix switches you to Code view and creates a handler for the grid control s BeforeUpdate event.

    The BeforeUpdate event is raised after the user clicks the Save button, but before the SQL Update statement in the SqlDataSourceControl is executed. The event therefore gives you an opportunity to get the user s edits and use them to set the parameters for the SQL Update statement.

    After you ve created the skeleton handler, add code so that the handler looks like the following:

    Sub MxDataGrid1_BeforeUpdate(source As Object,          e As MxDataGridUpdateEventArgs     Dim slideID As Strin     Dim slideshowName As Strin     Dim slideURL As Strin     Dim slideCaption As Strin     Dim slideDate As Strin     slideshowName = labelSlideshowName.Tex     slideID = e.Item.Cells(2).Tex     Dim tb As TextBo     tb = CType(e.Item.Cells(3).Controls(0), Te xtBox     slideURL = tb.Tex     tb = CType(e.Item.Cells(4).Controls(0), Te xtBox     slideCaption = tb.Tex     tb = CType(e.Item.Cells(5).Controls(0), Te xtBox     slideDate = tb.Tex      e.NewValues.Add("@slideshowname", slidesho wName     e.NewValues.Add("@slideid", slideID      e.NewValues.Add("@slideurl", slideURL     e.NewValues.Add("@slidecaption", slideCapt ion     e.NewValues.Add("@slidedate", slideDate End Sub

    The variable e, passed into the handler, is an object that gives you access to the information in the current grid row. As mentioned, you need to drill down a bit in order to get at the values that the row holds. The object e has a property named Item that contains the current row itself. The Item property in turn has a Cells collection that contains, as you would expect, the individual cells (columns) of the current row. We need to read values out of the cells that contain the slide ID, the slide URL, the caption, and the date. When the grid row is in edit mode, the values you need are stored, respectively, in the third, fourth, fifth, and sixth columns, meaning that the columns are cells 2, 3, 4, and 5. (Cells 0 and 1 contain the Save/ Cancel buttons and the Delete button.)

    You can get the slide ID easily by retrieving the Text property of the cell in which the data is displayed, as shown here:

    slideID = e.Item.Cells(2).Text

    The URL, caption, and date are not simply text in the cells, however. Instead, the values are in editable text boxes. Getting those values means digging even deeper into the grid row. Look at the code used to read the value out of the URL text box:

    Dim tb As TextBo tb = CType(e.Item.Cells(3).Controls(0), TextBo x slideURL = tb.Text 

    First you create a variable of type TextBox to hold the text box that you want to get out of the grid item. To actually get the text box, you have to drill farther down into the cell s Controls collection and read the first control out of the cell. (Cells can sometimes contain multiple controls, although not in this example; here we have only single text boxes in each cell.) Finally, you need to perform a cast, or conversion, to get the text box. As I say, cells can contain multiple controls, and these can be different types of controls, such as labels, text boxes, check boxes, and so on. Because the Controls collection can contain any type of control, the controls contained in the collection are typed as generic objects. If you want to manipulate a control you get out of the Controls collection, you need to cast it to the type you need. In this example, we call the Visual Basic .NET CType function to cast the generic object in the Controls collection into a TextBox object. Then, finally, we can read the text of the text box! Reading a text box value out of the grid is rather involved, isn t it? Once someone has shown the technique to you, however, it is at least comprehensible, even if it isn t intuitive.

    The code reads the values of the remaining text boxes in the same way, varying only in what cell the text box is in. After you ve gotten all the information for a slide, you can pass the values to the SQL Update statement that will be executed after this event handler has finished. Once again, the e object passed to the handler provides a special collection for this purpose the NewValues collection. The NewValues collection works essentially the same as the Parameters collection that you used to pass values to a SQL Select statement earlier in this chapter. When you add a new item to the NewValues collection, you specify the parameter name (for example, @slideshowname) and the value you want to pass (a local variable such as slideshowName).

    Note 

    Incidentally, when you perform an update using the code illustrated in this section, you always update all the values in the slide record. The code doesn t make any attempt to determine whether the user actually changed a value.

    Testing Editing Capabilities

    You ve now finished adding the editing capabilities to the page. The only thing left to do is test the page to make sure that you can edit individual slides. Run the page. When you re redirected to the slideshow master page, select a slideshow and click the Add/Edit Slides link to display the  AddSlides.aspx page.

    To test the Edit buttons, add a new slide. In the grid, find the new slide and click the Edit button. Change the text of the URL, caption, or date (or all three) in the text boxes, and then click Save. Check the grid to be sure that the edits you made were saved. Click the Edit button for another slide and make changes, and then click the Cancel button to confirm that your edits are discarded. When you ve finished, close the browser.




    Microsoft ASP. NET Web Matrix Starter Kit
    Microsoft ASP.NET Web Matrix Starter Kit (Bpg-Other)
    ISBN: 0735618569
    EAN: 2147483647
    Year: 2003
    Pages: 169
    Authors: Mike Pope
    BUY ON AMAZON

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net