Chapter 17. Working with Data-Bound DropDownLists, RadioButtons, and CheckBoxes

<feature><title></title>

In this hour, we will cover

  • Populating the items of a drop-down list with the results from a database query

  • Creating check boxes and radio buttons based on the results of a database query

  • Using the DropDownList control to filter the contents displayed in a GridView

  • The benefits of using database information versus hard-coding drop-down list, check box, and radio button values

</feature>

As we’ve seen over the past three hours, the data source controls enable us to easily work with database data. We simply specify what table and columns we want to work with and whether we need corresponding INSERT, UPDATE, and DELETE statements. When a data source control has been properly configured, one of a number of data Web controls can be used to interact with that data through an ASP.NET page. In addition to the GridView and DetailsView controls, ASP.NET includes a number of list controls that can also be bound to data source controls: the DropDownList, CheckBoxList, and RadioButtonList controls.

In Hour 11, “Collecting Input Using Drop-Down Lists, Radio Buttons, and Check Boxes,” we looked at using the DropDownList, RadioButton, and CheckBox controls in an ASP.NET page, but we had to explicitly provide the values for the drop-down list items, radio buttons, and check boxes. Now that we know how to work with databases, we can reexamine these controls from Hour 11 and see how to populate them with data from a database.

An Overview of the List Web Controls

ASP.NET includes a bevy of Web controls designed for collecting user input, many of which we examined in Hours 10 and 11. The list Web controls, a special class of input collection Web controls, present the user with a list of options. The DropDownList, which we examined in Hour 11, falls into this category of list Web controls because it presents users with a series of options from which they must pick one. Although the CheckBox and RadioButton controls represent a single check box or radio button and, therefore, aren’t list controls, often multiple radio buttons or check boxes are used in tandem to provide users with a list of check boxes or radio buttons to select among. ASP.NET does provide two Web controls designed to present a list of check boxes or radio buttons. These two Web controls—the CheckBoxList and RadioButtonList—are list Web controls.

The list Web controls share a number of features. Conceptually, they are all a collection of items of one sort or another. The DropDownList is a collection of drop-down list items; the CheckBoxList, a collection of check boxes; and the RadioButtonList, a collection of radio buttons. More concretely, they share a number of programmatic traits, such as

  • Each list Web control provides programmatic access to its items through the Items property.

  • Each item in a list Web control is an instance of the ListItem class.

  • Each list Web control can optionally be configured to induce a postback when an end user makes a change in the selected state of the control. (This is discussed in the “Automatically Posting Back When a List Web Control Changes” section later in this hour.)

  • If a list Web control’s selected item or items are changed across postbacks, the SelectedIndexChanged event is raised.

  • The list Web controls’ Items collection can be propagated statically, programmatically, or through a data source control.

In Hour 11 we saw how to assign the items of a DropDownList control statically. Recall that the DropDownList’s smart tag has an Edit Items link that, when clicked, displays the ListItem Collection Editor dialog box. This dialog box permits us to statically specify the items of a list control. The CheckBoxList and RadioButtonList also have a smart tag with an Edit Items option that likewise brings up the ListItem Collection Editor dialog box.

In addition to specifying a list Web control’s items statically, we can assign the values through a data source control. That is, we can add a SqlDataSource control to our page, configure it to grab a set of records from a database table, and then bind that data to the list Web control. For each record returned by the SqlDataSource, the list Web control adds an item to its list.

Binding Data to a List Web Control

Binding data to a list Web control is very similar to binding data to a GridView or DetailsView. The only difference is that whereas a GridView or DetailsView can be bound to a variable number of database table columns, list Web controls can be bound to, at most, two columns. The reason is that each item in a list control has two properties, Text and Value. The Text property is the value displayed onscreen—the text shown in the drop-down list item or the text of the radio button or check box—whereas the Value property is not displayed, but provides an additional bit of information about each item.

Let’s not get bogged down with the differences between the Text and Value properties at this point; if the distinction is not clear now, it will be as we work through some examples. For now, let’s practice binding database results to the various list Web controls.

Start by creating a new ASP.NET page named ListControls.aspx. Next, add a SqlDataSource control to the page and configure it to return all columns and all rows of the Books table. You don’t need to configure the SqlDataSource control to include the INSERT, UPDATE, and DELETE statements. After you have finished this, drag a DropDownList, CheckBoxList, and RadioButtonList onto the page, preceding each with text that shows the name of the control. After you have added the SqlDataSource control and the three list Web controls, your screen should look similar to Figure 17.1.

A SqlDataSource and the three list Web controls have been added to the page.

Figure 17.1. A SqlDataSource and the three list Web controls have been added to the page.

Each of these list Web controls has a smart tag with a Choose Data Source link. Clicking this link displays the Data Source Configuration Wizard, which prompts for the data source control to use and the column(s) to bind to the Text and Value properties of each list Web control. Take a moment to configure the data source for each of the three list Web controls, having each one display the Title column and use the BookID column as the value. Figure 17.2 shows this dialog box when configuring the DropDownList control’s data source.

Choose the data source control and the columns to bind to the list Web control.

Figure 17.2. Choose the data source control and the columns to bind to the list Web control.

After you specify a data source for the list Web control, the Design view in Visual Web Developer will change slightly; instead of using the word Unbound for the DropDownList, RadioButtonList, or CheckBoxList (see Figure 17.1), the word Databound is used instead. To see the actual values displayed in the drop-down list, check boxes, or radio buttons, you’ll need to view the ASP.NET page through a browser. Take a moment to do this and ensure that your screen looks similar to Figure 17.3.

The list Web controls have five items, one for each book in the Books table.

Figure 17.3. The list Web controls have five items, one for each book in the Books table.

Note that each list Web control has five items, one for each record returned by its SqlDataSource. The difference among the three list Web controls is the way they render their items.

The Benefits of Dynamically Populating a List Control

In Hour 11 we looked at how to populate the items in a DropDownList control statically, using the ListItem Collection Editor dialog box. Both the CheckBoxList and RadioButtonList can have their list items specified statically in this manner. Simply click the Edit Items link in their smart tags.

Although the list Web controls do support having their items set statically, it’s often advantageous to do so dynamically, through binding the control to a data source. The problem with statically assigning the items to a list control is that if there are changes to the items to be displayed in the future, you must visit each and every page that uses this data and update the list control appropriately. If you dynamically bind your items, though, and if any changes occur, you can just update the database table from which the items are retrieved and you’re done!

For example, in Hour 11 we looked at using a DropDownList that was statically populated with a list of ice cream flavors, from which we asked visitors to choose their favorite. These values were entered statically but could have been entered dynamically. That is, we could have created a table in our database called IceCreamFlavors that had two columns:

  • IceCreamFlavorIDA primary key, Auto-increment field of type int that uniquely identifies each ice cream flavor

  • FlavorAn nvarchar(100) column that contains the name of the flavor (Chocolate, Vanilla, and so on)

Then, in our ASP.NET page, we could use a SqlDataSource control to grab the contents of this table and bind it to the DropDownList. This may sound like a lot of work just to display some ice cream flavors, and this approach obviously isn’t as quick as just typing in a handful of flavors in the DropDownList’s ListItem Collection Editor dialog box. However, it will save you time if you need to replicate this functionality on other pages, if you expect the list of ice cream flavors to change in the future, or if you need to provide some association, for instance, in the database between users and their favorite ice cream flavors.

I encourage you to use dynamic list Web controls for all but the most trivial scenarios that are guaranteed not to change in the future, such as a drop-down list with gender options, Yes/No options, hours of the day, and so on.

By the Way

In Hour 13, “An Introduction to Databases,” we briefly discussed how many real-world databases are composed of multiple, related tables. With such relational database models, scenarios often occur in which you need to populate related data using a list Web control. For such scenarios it is of the utmost importance to grab the data dynamically from the database, rather than hard-coding in the related options statically.

Programmatically Responding to a Changed Selection

When using list Web controls on a web page, we are often interested in knowing when a list control’s selected item has changed. Each of the list controls contains a SelectedIndexChanged event that fires upon postback if the list control’s selection has changed. Returning to our earlier example, ListControls.aspx, add a Button Web control and a Label Web control to the page. Set the Button’s ID and Text properties to SubmitButton and Click Me, respectively. Set the Label’s ID property to Status, and clear out its Text property.

Next, create a SelectedIndexChanged event handler for the DropDownList. You can accomplish this by double-clicking the DropDownList in the Design view, or by going to the code view and choosing the DropDownList’s ID and the SelectedIndexChanged event from the drop-down lists at the top of the screen. After you have added this event handler, your ASP.NET page’s source code portion should look like this:

Partial Class ListControls
    Inherits System.Web.UI.Page

    Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged

    End Sub
End Class

This event handler—DropDownList1_SelectedIndexChanged—executes whenever the page is posted back and a change has occurred in the selected item of the DropDownList. To test this, add the following line of code in the event handler:

Status.Text = "The drop-down list value is now " & DropDownList1.SelectedValue

Set a breakpoint at this line by positioning your cursor on the line and pressing F9, or by clicking in the margin; next, start the debugger by going to the Debug menu and choosing Start. This loads the ASP.NET page in a browser. Notice that on the initial page load, the SelectedIndexChanged event does not fire because there’s been no change to the selected state of the DropDownList. At this point your screen should look similar to Figure 17.3, except with the addition of a button.

By the Way

The basics of debugging an ASP.NET web page were discussed in Hour 4, “Designing, Creating, and Testing ASP.NET Pages” Feel free to return to Hour 4 to refresh your memory, if needed.

Without changing the value of the DropDownList, click the button, posting back the ASP.NET page. Again, the SelectedIndexChanged event does not fire because the selected DropDownList item—Visual Studio Hacks—has yet to change. This time, however, select a different book from the DropDownList and click the button. Upon postback, the SelectedIndexChanged event will fire, and the debugger will break on the breakpoint we set. Continue debugging by pressing F5. The browser window should now refresh, displaying a message in the Status Label indicating the BookID value of the selected book (see Figure 17.4).

The Label displays the BookID of the currently selected book.

Figure 17.4. The Label displays the BookID of the currently selected book.

Note that if you click the button again without changing the book selection, the SelectedIndexChanged event does not fire. As we’ve seen, it fires only on the postback immediately following a change in the list Web control’s selection state.

As we discussed in Hour 9, “Web Form Basics,” server-side events and code, such as a list control’s SelectedIndexChanged event and its associated event handler, can fire and execute on the web server only when the browser explicitly rerequests the page (a postback). By default, changing the selection of a list control does not cause a postback. Therefore, the control’s SelectedIndexChanged event does not fire immediately after the user changes the selection state of a list control, but only when a postback ensues. For instance, in our previous example, you can change the drop-down list from The Number to Visual Studio Hacks, but the DropDownList Web control’s SelectedIndexChanged event doesn’t fire until the Click Me button is clicked, thereby causing a postback.

If the drop-down list’s selection was changed from The Number to Visual Studio Hacks to Fight Club, and then the Click Me button was clicked, the SelectedIndexChanged event would fire only once, because from the web server’s perspective, the drop-down list’s selection has changed only once, from The Number to Fight Club. Similarly, if the drop-down list is changed from The Number to Visual Studio Hacks, and then back to The Number, and then the Click Me button is clicked, the SelectedIndexChanged event won’t fire because from the web server’s perspective, no selection change has been made—when the web server initially rendered the page, the DropDownList Web control’s initial selection was The Number and on postback the selection was still The Number.

By the Way

In some scenarios, you might be interested to immediately know when a list Web control’s selection state has changed. For example, a page might have a “Quick Links” DropDownList that contains some of the popular pages on your website. In this case you might want to have a SelectedIndexChanged event handler that redirects the user to the appropriate page whenever the DropDownList value is changed. In such scenarios the page needs to post back as soon as the user changes her selection; the next section discusses how to add such behavior to the list controls.

At other times, you may not really care when a list control’s selection changes, but you are interested in what values are selected on postback. In this case, you can put your programmatic login in the Button Web control’s Click event handler, which will run when the page is posted back.

Automatically Posting Back When a List Web Control Changes

In the smart tags for the list Web controls, you may have noticed a check box labeled Enable AutoPostBack. This check box indicates the value of the control’s AutoPostBack property, which indicates whether the list Web control induces a postback upon having its selected state changed. As we’ve seen, by default the list controls don’t cause postbacks on their own; rather, a postback is typically caused by the user clicking a Button Web control. Therefore, with list Web controls, the end user can make any sort of change to the list control—checking or unchecking the check boxes of a CheckBoxList, selecting different radio buttons from the RadioButtonList, or choosing different options in the DropDownList—and our server-side code won’t know of these changes until the form is posted back.

However, we might want to be immediately alerted whenever a user changes the selection state of a list Web control. That is, if the user chooses a different DropDownList item, checks or unchecks a check box in a CheckBoxList, or picks a different radio button in a RadioButtonList, we might want to be notified right away, rather than having to wait for the user to click a button. We can implement this behavior by checking the Enable AutoPostBack check box in the list Web control’s smart tag. With this option selected, the list control is rendered with additional client-side JavaScript that causes a postback as soon as the user alters the selection state. On postback, the list control’s SelectedIndexChanged event fires.

The remainder of this hour focuses on using these three list Web controls in real-world situations. In the next section we’ll see an example of using a DropDownList to filter the results displayed in a GridView. In this example, the DropDownList’s AutoPostBack property will be set to True so that the data is automatically refreshed as soon as the DropDownList is changed. We’ll also examine using the RadioButtonList and CheckBoxList to collect and process user input.

Filtering Results Using the DropDownList

In the past three hours we’ve been working with the Books database table and have seen how to use a GridView to display all the books in this table. In Hour 14, “Accessing Data with the Data Source Web Controls,” we saw how to add hard-coded filtering expressions on the SqlDataSource control’s SelectCommand to limit the books returned.

Specifying hard-coded filtering expressions is one way to limit the data returned by a data source control, but we might rather allow the user visiting the web page to be able to specify how, exactly, the data is filtered. When specifying the values for a filter expression through the SqlDataSource control’s wizard, we can specify that the value be based on another Web control on the page, rather than a hard-coded value. For instance, we can craft a SqlDataSouce control so that its WHERE clause is based on the selected value of a DropDownList control.

To illustrate this, let’s first add an additional column to the Books table by which we can easily filter the records. Take a moment to add a Genre column of type nvarchar(50) to the Books table. Because there are existing records in the Books table, you’ll either need to give this column a default value or configure it to allow Nulls. For now, let the Genre column allow Nulls.

By the Way

If you need to review how to specify the definition of a SQL Server 2005 database table in Visual Web Developer, consult Hour 13.

Those with a database background know that rather than adding an nvarchar(50) Genre column, we should ideally create a new Genre lookup table, adding a foreign key GenreID to the Books table. Feel free to go this route, if this makes sense to you; if what I just said is Greek to you, don’t worry; just create the Genre column as discussed.

After you’ve added this new table column, view the table data in Visual Web Developer and enter values for the genres for each of the books. I used the genre Technology for Visual Studio Hacks and Create Your Own Website, the genre Business for The Number and the genre Fiction for The Catcher in the Rye and Fight Club.

Next, create a new ASP.NET page named DropDownList.aspx. When we’re done, this page will contain a DropDownList control that lists all the available genres and a GridView control that displays those books that match the genre selected in the DropDownList. This requires two SqlDataSource controls: one to retrieve the list of genres for the DropDownList and the other to grab those books that are of the selected genre for the GridView.

Listing the Genres in a DropDownList

Let’s first concentrate on adding the DropDownList of genres. The DropDownList of genres will list each of the genres defined in the Books table. The user visiting the page can then filter the GridView results depending on the selected genre from the DropDownList. To create a DropDownList control listing the available genre choices, perform the following steps:

  1. Add a SqlDataSource control that is configured to return just the Genre column from the Books table. Have the results ordered by the value of the Genre column in ascending order.

  2. After completing the wizard, change this control’s ID property from SqlDataSource1 to a more descriptive GenresDataSource.

  3. Enter the text Choose a genre: and then add a DropDownList control to the page. Bind the DropDownList control to the GenresDataSource SqlDataSource, using the Genre column as both the text and values of the DropDownList’s items.

  4. Change the DropDownList control’s ID from DropDownList1 to a more descriptive Genres.

At this point, test your ASP.NET page through a browser (see Figure 17.5). Notice that the drop-down list contains five items—one for each record in the Books table—even though the table contains only three unique genre values.

A drop-down list item is available for each record in the Books table, rather than one for each unique genre.

Figure 17.5. A drop-down list item is available for each record in the Books table, rather than one for each unique genre.

To remedy this, we need to configure the SqlDataSource to return only the unique genres in the Books table. To accomplish this, reopen the SqlDataSource control’s wizard, and in the Configure the Select Statement screen, check the Return Only Unique Rows check box, as shown in Figure 17.6.

Only the unique genres will be returned.

Figure 17.6. Only the unique genres will be returned.

Watch Out!

For this solution to work as needed, it is important that the SELECT statement return only a single column, Genre.

The Return Only Unique Rows check box looks at all columns in the SELECT clause and considers a row a duplicate only if every value in the column list is equal to some other row’s. That is, if you have the SELECT statement return, for instance, Title and Genre, currently all five records will be returned. If there were two books in the database with the same title and genre, then, and only then, would only one of these records be returned.

After making this change, view the page through a browser again. This time the drop-down list will have only three items: Business, Fiction, and Technology.

Filtering the Data Based on the Selected Genre

Our next step is to add a GridView control that displays only those books that belong to the selected genre. Let’s first add a GridView that displays all books from the Books table. We’ve done this many times in the past two hours, so this should be an easy task. Just drag a SqlDataSource onto the page and configure it to return all columns and all records from the Books table. As we did with the genre-returning SqlDataSource, change this SqlDataSource control’s ID from SqlDataSource1 to a more descriptive BooksDataSource. Next, add a GridView to the ASP.NET page, binding it to the BooksDataSource data source control. Rename the GridView’s ID property to Books.

Take a moment to test the page in a browser. Because the BooksDataSource SqlDataSource isn’t filtering the books based on the genre yet, the GridView shows all the books, regardless of what genre is selected from the drop-down list. Our next step, then, is to implement filtering within the BooksDataSource SqlDataSource. To accomplish this, return to the data source control’s wizard and from the Configure Select Statement screen, click the WHERE button to bring up the Add WHERE Clause dialog box.

We want to add a WHERE clause to the SELECT statement that looks like this:

SELECT *
FROM [Books]
WHERE [Genre] = Genre selected in the DropDownList

Because we want this WHERE clause to operate on the Genre column, choose Genre from the Column drop-down list. Select the = operator from the Operator drop-down list and then, from the Source drop-down list, choose Control because we want the filter expression to be based on the value of a Web control on the page. Choosing the Control option updates the Parameter Properties box in the upper-right corner to provide a drop-down list titled Control ID and a text box titled Default Value. From the Control ID drop-down list, select the Genres control (the ID of our DropDownList); you don’t need to pick a default value, so you can leave this text box blank.

Make sure your screen looks similar to Figure 17.7 and then click the Add button to add the parameter to the SqlDataSource. Click OK to return to the Configure the Select Statement screen and then complete the wizard.

Add a WHERE clause parameter whose value is the selected value of the genres DropDownList.

Figure 17.7. Add a WHERE clause parameter whose value is the selected value of the genres DropDownList.

View the ASP.NET page through a browser again. This time, when the page first loads, the GridView should display only one book, The Number, because that’s the only book that falls within the Business genre (see Figure 17.8). Go ahead and try changing the drop-down list to another genre. Nothing happens! We still see the GridView with one record, listing The Number. The reason is that we’ve yet to enable AutoPostBack in the DropDownList control. Simply changing the DropDownList doesn’t cause a postback unless the DropDownList’s AutoPostBack property is set to True. Take a moment to fix this and then revisit the page. Now selecting a different genre from the drop-down list invokes a postback and causes the GridView to be updated (see Figure 17.9).

The DropDownList.aspx page, when first visited.

Figure 17.8. The DropDownList.aspx page, when first visited.

The page after the user has changed the drop-down list’s selection from Business to Technology.

Figure 17.9. The page after the user has changed the drop-down list’s selection from Business to Technology.

By the Way

Setting the DropDownList’s AutoPostBack property to True was not necessary. We could have optionally added a Button Web control to the page after the DropDownList with a Text property like “Refresh.” Clicking this would have induced a postback and refreshed the GridView based on the user’s drop-down list selection. In essence, we need a postback to refresh the GridView’s display, which can be accomplished by either setting the DropDownList’s AutoPostBack property to True or by adding a Button that the user can click to instigate the postback.

Collecting User Input with CheckBoxLists and RadioButtonLists

In Hour 11 we saw how to use the CheckBox and RadioButton controls to collect user input. When using these individual controls, we had to manually add one CheckBox or one RadioButton control for each check box or radio button needed. Rather than using a series of single CheckBox or RadioButton controls, we can use, instead, the CheckBoxList or RadioButtonList.

By the Way

Recall that a series of check boxes allows the user to select zero to many items from the list of choices. With radio buttons, however, the user is restricted to selecting one of the available choices.

The CheckBoxList and RadioButtonList’s items can be specified statically via the ListItem Collection Editor dialog box, which you can reach by clicking the Edit Items link in the control’s smart tag. The process for adding items to a CheckBoxList or RadioButtonList using the ListItem Collection Editor dialog box is identical to adding items this way for a DropDownList. These steps were covered in detail in Hour 11.

The CheckBoxList and RadioButtonList can also be bound to a data source control as we saw in the “Binding Data to a List Web Control” section earlier in this hour. What we didn’t look at earlier, though, was how to determine what item or items, in the case of a CheckBoxList, were selected by the user. There are a couple ways to accomplish this:

  • Enumerate the list control’s items, checking each item to see if it has been selected.

  • Use the SelectedItem property to get a reference to the item that was selected.

Let’s examine both of these techniques. First, let’s create a new ASP.NET page named CheckAndRadio.aspx and add a SqlDataSource control, a CheckBoxList, and a RadioButtonList. Configure the SqlDataSource to return all columns and all records from the Books table. Bind this SqlDataSource to both the CheckBoxList and RadioButtonList, having the list controls display the Title column with their values set to the BookID column.

Finally, add a Button Web control and a Label Web control, setting their ID properties to SubmitButton and Results, respectively. Set the Button’s Text property to Click Me and then create an event handler for its Click event. Clear out the Text property of the Label control.

Take a moment to view the page through a browser. You should see a series of check boxes listing each of the five books in the table, followed by a series of radio buttons listing the same books.

Enumerating the List Web Control’s List Items

As discussed earlier in this hour, all three list Web controls have an Items property that is a collection of list items. This collection can be programmatically enumerated using the following code:

'Enumerate the list of items in the CheckBoxList
For Each li As ListItem In listWebControlID.Items
  ' Work with the list item, li
Next

Within the For Each loop, you can access the properties of the current list item (li); the germane ones are

  • SelectedA Boolean value indicating whether the list item has been selected by the user

  • TextThe displayed text of the list item

  • ValueThe value assigned to the list item

If we wanted to display a list of the selected items in the Results Label Web control, we could use the following code:

Results.Text = String.Empty

'Enumerate the list of items in the CheckBoxList
For Each li As ListItem In CheckBoxList1.Items
    If li.Selected Then
        Results.Text &= li.Text & " was selected!<br />"
    End If
Next

This code starts by clearing out the Text property of the Label control and then enumerates the list items of the CheckBoxList CheckBoxList1. If an item is selected—that is, if li.Selected is True—the Label’s Text property has appended a string indicating that the particular list item was selected. (The <br /> in the string is an HTML element that adds a breaking line; it’s used to help improve the readability of the output in the page.)

Figure 17.10 shows this ASP.NET page. Note that for each selected check box a corresponding message is displayed in the Label. (This approach works equally well for RadioButtonLists.)

The Label’s output is dictated by what check boxes were selected.

Figure 17.10. The Label’s output is dictated by what check boxes were selected.

Using SelectedItem and SelectedValue

In Hour 11 we saw how to programmatically determine the selected item or value of the DropDownList using the SelectedItem and SelectedValue properties. The SelectedItem property returns the ListItem instance of the selected item; SelectedValue returns the value of the selected item. Both the RadioButtonList and CheckBoxList have these two properties as well; however, more care must be taken when using these properties with either of these two controls.

When you’re using a RadioButtonList or CheckBoxList, understand that the user may not choose any item. With either of these controls, the user can avoid selecting a check box or radio button. (This concern doesn’t exist with the DropDownList control.) Before using these properties, then, you must first ensure that a value was selected. The simplest way to ensure that a value has been selected is to test to see whether the SelectedItem property is equivalent to Nothing; if it is, that means an item was not selected.

We can use the following code to proceed within the conditional only if an item has been selected. That is, we test to see whether SelectedItem is not Nothing and, if so, we can then work with the SelectedItem or SelectedValue properties (see Figure 17.11):

'See what item was selected in the RadioButtonList
If RadioButtonList1.SelectedItem IsNot Nothing Then
    results.Text &= "From the RadioButtonList you selected " & RadioButtonList1.SelectedItem.Text
End If
The selected radio button’s text is displayed in the Results Label.

Figure 17.11. The selected radio button’s text is displayed in the Results Label.

Watch Out!

If you do not use a conditional statement to ensure that SelectedItem is not Nothing, you will get an exception if the user has not selected any item and you try to access the SelectedValue property or one of the properties of SelectedItem (such as SelectedItem.Text).

Another concern with SelectedItem and SelectedValue is that they return a single ListItem instance or value. How does this work with the CheckBoxList, which might have multiple selected items? SelectedItem and SelectedValue return the first selected item from the list. Therefore, we typically use SelectedItem or SelectedValue only with DropDownLists or RadioButtonLists. For determining the selected items in a CheckBoxList, stick with enumerating the CheckBoxList’s Items collection, as we saw in the previous section.

Customizing the Appearance of the RadioButtonList and CheckBoxList Controls

Like the other ASP.NET Web controls we’ve examined throughout this book, the RadioButtonList and CheckBoxList controls have Font, ForeColor, BackColor, and other common formatting properties we’ve seen before. As with other Web controls, these properties can be found in the Appearance section within the Properties window.

The RadioButtonList and CheckBoxList also have some properties in the Layout section worth noting. By default, both the RadioButtonList and CheckBoxList are rendered in a single column. Although a one-column layout will likely suffice for CheckBoxLists or RadioButtonLists with a small number of items, displaying dozens of check boxes or radio buttons in this vertical, single-column manner can easily chew up a lot of screen real estate. Rather than confining the items to a single column, we might want to have the check boxes or radio buttons span multiple columns.

To accomplish this, use the RepeatColumns property, which specifies how many columns to display and can be assigned any non-negative integer value. The RepeatDirection property indicates the direction the items are laid out and can be either Horizontal or Vertical (the default).

Figure 17.12 shows a CheckBoxList and RadioButtonList with three columns. The figure also illustrates the effects of the RepeatDirection property: The CheckBoxList has its RepeatDirection property set to Vertical, whereas the RadioButtonList’s is set to Horizontal. The results here are ordered by BookID, so Visual Studio Hacks is the first book, then Create Your Own Website, followed by The Number, and so on. As you can see, with the CheckBoxList, the first two books are in the first column, the second two in the second column, and so on. In essence, the output is grouped by row. With the RadioButtonList’s Horizontal RepeatDirection value, the output is grouped by column, with the first three books in the first column and last two books in the second column.

A RadioButtonList and CheckBoxList, with RepeatColumns set to 3.

Figure 17.12. A RadioButtonList and CheckBoxList, with RepeatColumns set to 3.

Summary

In this hour we examined the ASP.NET list Web controls: the DropDownList, CheckBoxList, and RadioButtonList. These three controls are composed of a series of list items that can be specified statically, programmatically, or through data binding. The manner by which these three controls differ is in how they render their list items. A DropDownList control renders as a drop-down list, with each item an option in the list. A CheckBoxList renders each of its items as a check box, and the RadioButtonList renders its items as radio buttons.

A common use of these controls is to list a particular column from a database table, enabling a visitor to easily filter displayed results. We saw an example of this in the “Filtering Results Using the DropDownList” section. In our example, a DropDownList contained the various genres, and a GridView displayed only those books of the selected genre.

Q&A

Q.

Earlier in this hour we worked on an example of filtering a GridView’s data using a DropDownList. Would it have been possible to use a RadioButtonList in place of the DropDownList?

A.

Sure, a RadioButtonList would have worked equally as well; in fact, exercise 1 asks you to build an ASP.NET page that filters the data displayed using a RadioButtonList.

When using a RadioButtonList to filter results, however, there is one point to keep in mind: by default, a RadioButtonList doesn’t have a selected item. Therefore, when the page first loads the parameter used to filter, the SqlDataSource will be missing and an exception will be raised. To circumvent this problem, you’ll need to add a default value to the parameter when constructing your WHERE clause parameter in the SqlDataSource control’s wizard. Use as a default value one of the values of the Genre column, such as Business, or a blank string if you don’t want any results returned initially.

Q.

When filtering the GridView’s data using a DropDownList, the DropDownList defaulted to the first option, Business. Consequently, when the page is first visited the GridView lists those books in the Business genre. How would I go about adding a “Choose a Genre” item to the DropDownList that would be selected by default and, when selected, would not display any books in the GridView?

A.

To add a “Show All Genres” option to the DropDownList you need to add the “Show All Genres” option through the ListItem Collection Editor dialog box. As discussed in Hour 11, this dialog box is accessible through the Properties window. Set the new list item’s Text property to Choose a Genre and its Value property to -1 (or some other value that does not map to a valid Genre value).

By default, when database data is bound to a DropDownList it overwrites any statically added list items (such as the “Show All Genres” option). To override this behavior and append the data bound items those list items added statically, set the DropDownList’s AppendDataBoundItems property to True. That’s all there is to it!

Workshop

Quiz

1.

Name some of the ways in which the three list Web controls examined in this hour are similar to one another.

2.

Name some ways in which the list Web controls differ from one another.

3.

What is the name of the event that is raised when a list Web control’s selected state is changed across postbacks?

4.

What properties must you set to have the RadioButtonList or CheckBoxList controls render their items laid out horizontally using multiple columns?

5.

The DropDownList, RadioButtonList, and CheckBoxList controls all have an AutoPostBack property. What happens when this property is set to True?

Answers

1.

All are composed of list items and contain a similar set of base properties—Items, SelectedItem, SelectedValue, and so on. They all have a SelectedIndexChanged event that fires on postback if the selected state of the control has changed. Additionally, they all can have their list items specified in one of three ways: statically, through the ListItem Collection Editor dialog box; programmatically; and through a data source control.

2.

Each list Web control renders its list items differently. The DropDownList will always have one selected item, whereas the RadioButtonList can have zero or one, and the CheckBoxList can have zero to many selected items.

3.

SelectedIndexChanged.

4.

The RepeatColumns property specifies how many columns the RadioButtonList or CheckBoxList’s items will use; the RepeatDirection property indicates whether the items are laid out vertically or horizontally.

5.

When AutoPostBack is set to True, any client-side change in the control’s selection state causes a postback. For example, with a DropDownList whose AutoPostBack property is set to True, when the user chooses a new option from the list, the page automatically posts back and the DropDownList’s SelectedIndexChanged event is fired.

Exercises

1.

Using the same techniques discussed in the “Filtering Results Using the DropDownList” section, create an ASP.NET page that uses a GridView to display the books from the Books table and a RadioButtonList of all the authors to allow the user to filter the books displayed. (Be sure to set the RadioButtonList’s AutoPostBack property to True.)

As in our earlier example, make sure that the RadioButtonList displays only unique author names. Also, because on the initial page load, the RadioButtonList will not have any item selected, you’ll need to set a default value for the parameter you create in the GridView’s SqlDataSource Wizard. Set the default parameter value to a blank string. With this setting, when the page first loads, before a user selects an author from the list of radio buttons, the GridView should not be shown because there should be no authors with a blank string. Upon selecting a new author, the page will post back and the books that the selected author has written will be displayed.

When testing this, be sure to edit the Books table so that there are at least two books written by the same author. Also, take a moment to set the GridView’s EmptyDataText property to an applicable message. Recall that the value of this property is displayed when binding a GridView to a data source control that returns no records, as is the case with this exercise when the user first visits the page, before selecting an author.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.105.84