Displaying a List with the List Box


A list box is used to present a list of items to a user. You can add items to, and remove items from, the list at any time with very little Visual C# code. In addition, you can set up a list box so that a user can select only a single item or multiple items. When a list box contains more items than it can show due to the size of the control, scrollbars are automatically displayed.

By the Way

The cousin of the list box is the combo box, which looks like a text box with a down-arrow button at its right side. Clicking a combo box's button causes the control to display a drop-down list box. Working with the list of a combo box is pretty much identical to working with a list box, so I'll discuss the details of list manipulation in this section and then discuss the features specific to the combo box in the next section.


You're not going to be adding a list box or combo box to your Picture Viewer project at this time, so follow these steps to create a new project:

1.

Create a new Windows Application project titled Lists.

2.

Right-click Form1.cs in the Solution Explorer, choose Rename, and then change the name of the default form to fclsLists.cs and set its Text property to Lists Example.

3.

Add a new List Box control to the form by double-clicking the ListBox item in the toolbox and then set the properties of the list box as follows:

Property

Value

Name

lstPinkFloydAlbums

Location

64,21

Size

160,121


Every item contained in a list box is a member of the list box's Items collection. Working with items, including adding and removing items, is performed using the Items collection. You'll most often manipulate the Items collection using code (which I'll show you a little later in this hour), but you can also work with the collection at design time by using the Properties window.

Manipulating Items at Design Time

The Items collection is available as a property of the list box. Locate the Items property in the Properties window and click it to select it. The familiar button with three dots appears, indicating that you can do advanced things with this property. Click the button now to show the String Collection Editor. To add items to the collection, simply enter the items into the text boxone item to a line.

Enter the following items:

  • Atom Heart Mother

  • A Saucerful of Secrets

  • Wish You Were Here

  • Animals

  • Echoes

  • Meddle

When you're finished, your screen should look like that shown in Figure 7.12. Click OK to commit your entries and close the window. Notice that the list box contains the items that you entered.

Figure 7.12. Use this dialog box to manipulate an Items collection at design time.


Manipulating Items at Runtime

In Hour 3, "Understanding Objects and Collections," you learned about objects, properties, methods, and collections. All this knowledge comes into play when manipulating lists at runtime. The Items property of a list box (and a combo box, for that matter) is an object property that returns a collection (collections in many ways are like objectsthey have properties and methods). To manipulate list items, you manipulate the Items collection.

A list can contain duplicate values, as you'll see in this example. Because of this, Visual C# 2005 needs a mechanism other than an item's text to treat each item in a list as unique. This is done by assigning each item in an Items collection a unique index. The first item in the list has an index of 0, the second an index of 1, and so on. The index is the ordinal position of an item relative to the first item in the Items collectionnot the first item visible in the list.

Adding Items to a List

New items are added to the Items collection using the Add() method of the Items collection. You're now going to create a button that adds an album to the list. Add a new button to the form and set its properties as follows:

Property

Value

Name

btnAddItem

Location

95,148

Size

96,23

Text

Add an Item


Double-click the button to access its Click event and add the following code:

lstPinkFloydAlbums.Items.Add("Dark Side of the Moon");


Notice that the Add() method accepts a string argumentthe text to add to the list.

By the Way

Unlike items added at design time, items added through code aren't preserved when the program ends.


Press F5 to run the project now and click the button. When you do, the new album is added to the bottom of the list. Clicking the button a second time adds another item to the list with the same album name. The list box doesn't care whether the item already exists in the list; each call to the Add() method of the Items collection adds a new item to the list.

The Add() method of the Items collection can be called as a function, in which case it returns the index (ordinal position of the newly added item in the underlying collection), as in the following:

int intIndex; intIndex = lstPinkFloydAlbums.Items.Add("Dark Side of the Moon");


Knowing the index of an item can be useful, as you will see.

Stop the running project and save your work before continuing.

Did you Know?

To add an item to an Items collection at a specific location in the list, use the Insert() method. The Insert() method accepts an index in addition to text. For example, to add an item at the top of the list you could use a statement such as lstPinkFloydAlbums.Items.Insert(0,"Dark Side of the Moon");. Remember, the first item in the list has an index of 0.


Removing Items from a List

Removing an individual item from a list is as easy as adding an item and requires only a single method call: a call to the Remove() method of the Items collection. The Remove method accepts a string, which is the text of the item to remove. You're now going to create a button that removes an item from the list.

Display the form designer now and create a new button on the form. Set the button's properties as follows:

Property

Value

Name

btnRemoveItem

Location

95,177

Size

96,23

Text

Remove an Item


Double-click the new button to access its Click event and enter the following statement:

lstPinkFloydAlbums.Items.Remove("Dark Side of the Moon");


The Remove() method tells Visual C# to search the Items collection, starting at the first item (index = 0), and to remove the first item found that matches the specified text. Remember, you can have multiple items with the same text. The Remove() method removes only the first occurrence. After the text is found and removed, Visual C# stops looking.

Press F5 to run the project again. Click the Add an Item button a few times to add Dark Side of the Moon to the list (see Figure 7.13). Next, click the Remove an Item button and notice how Visual C# finds and removes one instance of the specified album.

Figure 7.13. The list box can contain duplicate entries, but each entry is a unique item in the Items collection.


Did you Know?

To remove an item at a specific index, use the RemoveAt() method. For example, to remove the first item in the list, you would use the following statement: lstPinkFloydAlbums.Items.RemoveAt(0);.


Stop the running project and save your work.

Clearing a List

To completely clear the contents of a list box, use the Clear() method. You're now going to add a button to the form that, when clicked, clears the list. Add a new button to the form and set the button's properties as follows:

Property

Value

Name

btnClearList

Location

95,206

Size

96,23

Text

Clear List


Double-click the new button to access its Click event and enter the following statement:

lstPinkFloydAlbums.Items.Clear();


Press F5 to run the project, and then click the Clear List button. The Clear() method doesn't care whether an item was added at design time or runtime; Clear() always removes all items from the list. Stop the project and again save your work.

Did you Know?

Remember that the Add(), Insert(), Remove(), RemoveAt(), and Clear() methods are all methods of the Items collection, not of the list box itself. If you forget that these are members of the Items collection, you might be confused when you don't find them when you enter a period after typing a list box's name in code.


Retrieving Information About the Selected Item in a List

Two properties provide information about the selected item: SelectedItem and SelectedIndex. It's important to note that these are properties of the list box itself, not of the Items collection of a list box. The SelectedItem method returns the text of the currently selected item. If no item is selected, the method returns an empty string. It is sometimes desirable to know the index of the selected item. This is obtained using the SelectedIndex property of the list box. As you know, the first item in a list has the index of 0. If no item is selected, SelectedIndex returns 1, which is never a valid index for an item.

You're now going to add a button to the form that, when clicked, displays the selected item's text and index in a message box. Add a new button to the form and set its properties as follows:

Property

Value

Name

btnShowItem

Location

95,235

Size

96,23

Text

Show Selected


Double-click the new button to access its Click event and enter the following statement (be sure to press Enter at the end of the first line):

MessageBox.Show("You selected " + lstPinkFloydAlbums.SelectedItem +       " which has an index of " + lstPinkFloydAlbums.SelectedIndex);


MessageBox.Show() is a Visual C# function used to show a message to the user. You'll learn about MessageBox.Show()in detail in Hour 17, "Interacting with Users."

Press F5 to run the project and click the Show Selected button. Notice that because nothing is selected, the message box doesn't read quite right, and it says that the selected index is -1 (which indicates nothing is selected). Click an item in the list to select it, and then click Show Selected again. This time, you'll see the text of the selected item and its index in the message box. Stop the running project and save your work.

By the Way

You can set up a list box to allow multiple items to be selected at once. To do this, you change the SelectionMode property of the list box to MultiSimple (clicking an item toggles its selected state) or MultiExtended (you have to hold down Ctrl or Shift to select multiple items). To determine which items are selected in a multiselection list box, use the list box's SelectedItems collection.


Sorting a List

List boxes and combo boxes have a Sorted property. This property is set to False when a control is first created. Changing this property value to True causes Visual C# to sort the contents of the list alphabetically. When the contents of a list are sorted, the index of each item in the Items collection is changed; therefore, you can't use an index value obtained prior to setting Sorted to True.

Sorted is a property, not a method. Realize that you don't have to call Sorted to sort the contents of a list; Visual C# enforces a sort order as long as the Sorted property is set to True. This means that all items added using the Add() method or the Insert() method are automatically inserted into the proper sorted location, in contrast to being inserted at the end of the list or in a specific location.




Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

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