Working with the Items Collection

I l @ ve RuBoard

Working with the Items Collection

The Items collection is a special property of type ListItemCollection in the System.Web.UI.WebControls namespace and is shared by all ASP.NET list controls. This class does the grunt work in managing the list items for each list control. Table 6.2 shows a summary of the properties and methods for the ListItemCollection class. Please take a moment to review them before we move on with an example of manipulating the items in a list control programmatically.

Table 6.2. Summary of the Properties and Methods of the ListItemCollection Class
Name Item Description
Add Method Overloaded. Adds a new item to the collection by supplying either a ListItem object or string value
All Property Gets an array of type ListItem of all items in the list
Clear Method Removes all items from the list
Contains Method Indicates whether or not the supplied item is in the list
Count Property Gets the number of items in the list
IndexOf Method Gets the ordinal for the specified item in the list
Insert Method Overloaded. Inserts an item into the list at the given index location based on the supplied ListItem object or string value
Item Method Gets the item referenced by the given index
Remove Method Overloaded. Removes the item in the list matching the specified ListItem or string value
RemoveAt Method Removes the item in the list matching the specified index

TIP

Unless you've gotten an in-depth look at the .NET languages already, you may be wondering about certain methods in Table 6.2. With the language enhancements of VB.NET and the introduction of C#, .NET developers can now take advantage of overloaded methods. These methods share the same name and return types, but have different signatures or number and types of arguments. This feature allows for cleaner and more flexible code.


Now that you've taken a peek at the Items collection, let's extend the previous example. Because we've already established that we can't use the SelectedIndex property to retrieve multiple selections, let's tackle the problem from a different angle. Listing 6.7 shows the modified event handler to handle multiple selections in the list box.

Listing 6.7 Using the Items collection to handle multiple selections in a ListBox control.
 Sub UpdateButton_Click(sender As Object, e As EventArgs)     Dim UserItem as ListItem     GroupList.ClearSelection()     For Each UserItem in UserList.Items         If UserItem.Selected = True Then             GroupList.Items.Item(UserList.Items.IndexOf(UserItem)).Selected  = True         End If     Next End Sub 

We've introduced several new methods here, so let's walk through the listing. The first call we make is to the ClearSelection method of the second list control to unselect any currently selected items. Then we simply loop through the Items collection of the first list control and test each item's Selected property. If the current item is selected, we need to select the corresponding item in the second list control. To do this, we first have to determine the ordinal for the current ListItem in the loop. We find this value by passing the current item, UserItem , to the IndexOf method of the Items collection of the first list control. We can then pass the return value of this method to the Item method of the Items property of the second list control to get a reference to the ListItem we're currently after. We then set its Selected property to True and proceed to the next item in the list. Because the Item method is the indexer for the collection, you may optionally use this syntax to reference a member of the Items collection:

 GroupList.Items(  index  ) 

Note that we omitted the Item method and passed the ordinal value to the Items collection directly. Either syntax is acceptable, but the first approach is more descriptive.

Adding Items with the Add Method

So far, you've seen how easy it is to manipulate list controls with ASP.NET, but the platform's true power for developers is the new ability to add and remove list items programmatically. Listing 6.8 outlines how easy it is to add items to a list control, and Figure 6.3 shows the output.

Figure 6.3. The output from the code in Listing 6.8.

Listing 6.8 Using the Add method to add items to the CheckBoxList control (6chklst01.aspx).
 <%@ Page language="vb" autoeventwireup="false" codebehind=""%> <html> <head> <script language="VB" runat="server" ID=Script1>     Sub AddButton_Click(sender As Object, e As EventArgs)         ItemList.Items.Add(ItemText.Text)     End Sub </script> </head> <body> <form runat="server">     <h3>Adding items with the Add method</h3>     Item text: <br>     <asp:textbox id="ItemText" runat="Server" />     <asp:button text="Add" runat="server"         ID="AddButton" onclick="AddButton_Click"/>     <br>     <asp:checkboxlist id="ItemList" runat="server"/> </form> </body> </html> 

In this example, we introduce another type of list control, the CheckBoxList control. You generally use this control when you need to present the user with options for a multiple-choice question when more than one answer is allowed. If your scenario requires only one item to be selected, you should use the RadioButtonList introduced later in this chapter.

In this example, simply enter some text in the text box and click the Add button to add a new item to the list. However, you might have noticed that nothing prevents us from adding duplicates. Most of the time, we would not want duplicate items in the list, so to prevent this, we use the Contains method of the Items collection, as shown in Listing 6.9.

Listing 6.9 Preventing duplicates when adding items to the ListBox control.
 Dim NewItem = New ListItem(ItemText.Text) If Not ItemList.Items.Contains(NewItem) Then     ItemList.Items.Add(ItemText.Text) End If 

The Contains method expects an argument of type ListItem , so we create our own item named NewItem from the supplied text. We then simply pass the item to the Contains method of the Items collection, which tells us if the item already is in the list. If the item is not in the list, we proceed to add the item as in the previous example.

Populating List Controls Based on User Selection

Now that you have a handle on adding items to the list, let's consider a more real-world example. In designing Web-based applications, the need often arises to populate one list based on the selection of another list. You probably already have a good idea how to do this, so let's walk through an example. We're going to populate a list of vehicle models based on the vehicle make the user selects. Normally we would get the data for this kind of information from an external data source, such as a database or XML file. We'll hard-code the entries for now, as shown in Listing 6.10, and we'll discuss databinding list options a little later in the chapter. Figure 6.4 shows the output from Listing 6.10.

Figure 6.4. The output from the code in Listing 6.10.

Listing 6.10 Using the Items collection to handle multiple selections in a ListBox control (6radlst01.aspx).
 <%@ Page language="vb" autoeventwireup="false" codebehind=""%> <html> <head> <script language="VB" runat="server">     Sub MakesList_SelectedIndexChanged(sender As Object, e As EventArgs)         ModelsList.Items.Clear()         Select Case MakesList.SelectedItem.Value             Case "GMC"                 ModelsList.Items.Add("Sierra")                 ModelsList.Items.Add("Yukon")                 ModelsList.Items.Add("Yukon XL")                 ModelsList.Items.Add("Sonoma")             Case "Chevrolet"                 ModelsList.Items.Add("Silverado")                 ModelsList.Items.Add("Tahoe")                 ModelsList.Items.Add("Suburban")                 ModelsList.Items.Add("S-15")                 ModelsList.Items.Add("Monte Carlo")             Case "Pontiac"                 ModelsList.Items.Add("Grand AM")                 ModelsList.Items.Add("Grand Prix")                 ModelsList.Items.Add("Bonnevile")         End Select End Sub </script> </head> <body> <form runat="server"> <h3>Adding list items based upon user selection</h3> <TABLE WIDTH="300" BORDER="0" CELLSPACING="1" CELLPADDING="1">     <TR>         <TD NOWRAP>Makes:</TD>         <TD NOWRAP>Models:</TD>     </TR>     <TR>         <TD NOWRAP valign="top">             <asp:radiobuttonlist id="MakesList" runat="server"                 onselectedindexchanged="MakesList_SelectedIndexChanged"                 autopostback="True">                 <asp:ListItem>GMC</asp:ListItem>                 <asp:ListItem>Chevrolet</asp:ListItem>                 <asp:ListItem>Pontiac</asp:ListItem>             </asp: radiobuttonlist >         </TD>         <TD NOWRAP>             <asp: radiobuttonlist id="ModelsList" runat="server" />         </TD>     </TR> </TABLE> </form> </body> </html> 

You should have noticed that we introduced the RadioButtonList , the last list control of the chapter (woo-hoo!). We could just as easily have used any other two list controls, but I thought this was a good time to slip that one in. This example introduces two important methods of the Items collection: Clear and Add . Once the vehicle make is selected, the first thing we need to do is to remove all the models from the models list control. We do this simply by calling the Clear method on the control's Items collection. We now have an empty list to which we can add the corresponding vehicle models for the selected make. Now we can just call the Add method once for each model to be added to the list. Note that we are passing the model name as a string to the Add method; however, we could use this optional syntax:

 ModelsList.Items.Add(New ListItem("Yukon XL")) 

This second approach creates a new ListItem object and passes the object to the Add method. The first approach lets the list control create the ListItem object on the fly simply by passing in the item text. Either way is acceptable.

Removing Items with the Remove Method

Now that we've added items to the list controls, let's look at how to remove items in an example for the following scenario. You need to design an interface to maintain users and security groups for your new ASP.NET Web application. You need to have a list of available users and another list of current members of the security group . We'll make the second list control the members list, which initially will be empty. Listing 6.11 contains the full example. Please take a moment to look it over before we walk through it. Figure 6.5 shows the output.

Figure 6.5. The output from the code in Listing 6.11.

Listing 6.11 Using the Items collection to handle multiple selections in a ListBox control (6lstb05.aspx).
 <%@ Page language="vb" autoeventwireup="false" codebehind=""%> <html> <head> <script language="VB" runat="server">     Sub AddButton_Click(sender As Object, e As EventArgs)         Dim Users as ListItemCollection = New ListItemCollection()         Dim User as ListItem         For Each User in UserList.Items             If User.Selected Then                 Users.Add(User)             End If         Next         For Each User in Users                UserList.Items.Remove(User)                GroupList.Items.Add(User)         Next     End Sub     Sub RemoveButton_Click(sender As Object, e As EventArgs)         Dim Users as ListItemCollection = New ListItemCollection()         Dim User as ListItem         For Each User in GroupList.Items             If User.Selected Then                 Users.Add(User)             End If         Next         For Each User in Users                UserList.Items.Add(User)                GroupList.Items.Remove(User)         Next      End Sub </script> </head> <body> <form runat="server"> <h3>Moving items between lists with Add and Remove</h3> <TABLE WIDTH="300" BORDER="0" CELLSPACING="1" CELLPADDING="1">     <TR>         <TD NOWRAP>Users:</TD>         <TD NOWRAP></TD>         <TD NOWRAP>Power Users:</TD>     </TR>     <TR>         <TD NOWRAP>             <asp:ListBox id="UserList" runat="server" Rows="4"              selectionmode="Multiple">                 <asp:ListItem>Paula</asp:ListItem>                 <asp:ListItem>Chris</asp:ListItem>                 <asp:ListItem>Eric</asp:ListItem>                 <asp:ListItem>Wynn</asp:ListItem>             </asp:ListBox>         </TD>         <TD NOWRAP>             <asp:button text="->" runat="server" ID="AddButton"              onclick="AddButton_Click"/>             <br>             <asp:button text="<-" runat="server" ID="RemoveButton"             onclick="RemoveButton_Click"/>         </TD>         <TD NOWRAP>             <asp:ListBox id="GroupList" runat="server" Rows="4"              selectionmode="Multiple">             </asp:ListBox>         </TD>     </TR> </TABLE> </form> </body> </html> 

In this example, we've created a pair of event handlers for the Add and Remove buttons on the form. Because they essentially do the same thing, only in reverse, we'll only walk through one of them. In each case, we begin by declaring an array of type ListItem , which we've named UserArray . We then iterate through the array and test the Selected property of each item. If the item is selected, we simply add it to the opposite list control while removing it from the current list.

You may be wondering why we didn't iterate through the Items collection directly the same way we did in previous examples. We must perform the extra step in this case by copying the items to an array first because removing items from the collection while it is being iterated produces an error.

I l @ ve RuBoard


Asp. Net. By Example
ASP.NET by Example
ISBN: 0789725622
EAN: 2147483647
Year: 2001
Pages: 154

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