User:Foxall/07

Ka Wiktionary

Hour 7. Working with the Traditional Controls[wax ka badal]

The previous two hours described in considerable detail how to work with forms. Forms are the foundation of a user interface but are rather useless by themselves. To create a usable interface, you'll need to use controls. Controls are the various widgets and doodads on a form with which a user interacts. Dozens of different types of controls exist, from the simple Label control used to display static text to the rather complicated Tree View control used to present trees of data like that found in Explorer. In this hour, I'll introduce you to the most common (and most simple) controls, which I call traditional controls. In the next hour, you'll learn about the more advanced controls that you can use to create professional-looking applications.

The highlights of this hour include the following:

  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch07lev1sec1.htm#ch07lev1sec1 Displaying static text with the Label control]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch07lev1sec2.htm#ch07lev1sec2 Allowing users to enter text using a text box]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch07lev1sec2.htm#ch07lev2sec5 Creating password fields]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch07lev1sec4.htm#ch07lev2sec10 Working with buttons]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch07lev1sec4.htm#ch07lev2sec8 Using panels, group boxes, check boxes, and option buttons]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch07lev1sec5.htm#ch07lev1sec5 Displaying lists with list boxes and combo boxes]

Displaying Static Text with the Label Control[wax ka badal]

Label controls are used to display static text to the user. By static, I mean that the user can't change the text directly (but you can change the text with code). Label controls are one of the most common controls used; fortunately, they're also one of the easiest. Labels are most often used to provide descriptive text for other controls, such as text boxes. Labels are also great for providing status-type information to a user, as well as for providing general instructions on a form.

Begin by creating a new Windows Application named Traditional Controls. Change the name of the default form to fclsControls, and change its Text property to Traditional Controls Example. Next, change the Main entry point to use flcsControls.

Add a new Label control to the form by double-clicking the Label item in the toolbox. The primary property of the Label control is the Text property, which determines the text displayed to the user. When a Label control is first added to a form, the Text property is set to the name of control�this isn't very useful. Set the properties of the new Label control as follows:

Property Value
Name lblMyLabel
Location 5,6
Size 100,25
Text Labels are for static text!

Notice how the label's text appears on two lines (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig01 Figure 7.1]). This occurs because the text is forced to fit within the size of a new Label control. In most cases, it's best to place label text on a single line. To do this, you could increase the width either by using the Properties window or by dragging the edge of the control, but there is an easier way. Double-click the Label control's AutoSize property now and notice how the label resizes itself automatically to fit the text on a single line. Double-clicking a property that accepts a set number of values cycles the property to the next value. The AutoSize property of new Label controls is false by default, so double-clicking this property changed it to true.

Allowing Users to Enter Text Using a Text Box 

A Label control is usually the best control for displaying text a user can't change. However, when you need to let users enter or edit text, the text box is the tool for the job. If you've ever typed information on a form, you've almost certainly used a text box. Add a new text box to your form now by double-clicking the TextBox item in the toolbox. Set the text box's properties as follows:

Property Value
Name txtMyTextBox
Location 128,4
Size 136,20

When you first create a new text box, its Text property is set to its default name (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig02 Figure 7.2]). Unfortunately, the Text property isn't automatically changed when you change the name of the text box (which you should always do), so I recommend that you clear out the Text property of new text boxes. Delete the text in the Text property now and notice that the text box appears empty on the form.

Figure 7.2. A new text box has its Text property set to its default name.

graphics/07fig02.jpg

Although you'll probably want to clear the Text property of most of your text boxes at design time, understanding certain aspects of the text box is easier when a text box contains text. Set the text box's Text property to This is sample text. Remember to press Enter or Tab to commit your property change.

 Specifying Text Alignment 

Both the TextBox and the Label controls have a TextAlign property (as do many other controls). The TextAlign property determines the alignment of the text within the control�very much like the justification setting in a word processor. You can select from Left, Center, or Right.

graphics/bulb.gif Label controls allow you to set the vertical alignment and the horizontal alignment using the TextAlign property. This works best when AutoSize is set to false.

Change the TextAlign property of the text box to Right, and see how the text becomes right-aligned within the text box. Next, change TextAlign to Center to see what center alignment looks like. As you can see, this property is pretty straightforward. Change the TextAlign property back to Left before continuing.

 Creating a Multiline Text Box 

In the previous hour, I talked about the sizing handles of a selected control. I mentioned how handles that can be sized appear filled with white, and handles that are locked appear with a gray center. Notice how only the left and right edges of the text box have white sizing handles. This means that you can adjust only the left and right edges of the control (you can alter only the width, not the height). This is because the text box is defined as a single-line text box, meaning it will display only one line of text. What would be the point of a really tall text box that showed only a single line?

To allow a text box to display multiple lines of text, set its Multiline property to true. Set the Multiline property of your text box to true now, and notice that all the sizing handles become white.

Change the Text property of the text box to This is sample text. A multiline text box will wrap its contents as necessary. Press Enter or Tab to commit the property change. Notice how the text box displays only part of what you entered because the control simply isn't big enough to show all the text (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig03 Figure 7.3]). Change the Size property to 136,60, and you'll then see the entire content of the text box (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig04 Figure 7.4]).

Figure 7.3. A text box may contain more text than it can display.

graphics/07fig03.jpg

Figure 7.4. A multiline text box can be sized as large as necessary.

graphics/07fig04.jpg

At times, you won't want a user to be able to interact with a control. For instance, you may implement a security model in your application, and if the user doesn't have the necessary privileges, you may not want the user to be able to alter data. The Enabled property, which almost every control has, determines whether the user can interact with the control. Change the Enabled property of the text box to false, and press F5 to run the project. Although no noticeable change occurs in the control in Design view, there is a big change to the control at runtime: the text appears in gray rather than black, and the text box won't accept the focus or allow you to change the text (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig05 Figure 7.5]).

Figure 7.5. You can't interact with a text box whose Enabled property is set to false.

graphics/07fig05.jpg

Stop the project now by choosing Stop Debugging from the Debug menu, and then change the control's Enabled property back to true.

 Adding Scrollbars 

Even though you can size a multiline text box, there may be times when the contents of the control are more than what can be displayed. If you believe that this is a possibility for a text box you're adding to a form, give the text box scrollbars by changing the ScrollBars property from None to Vertical, Horizontal, or Both.

graphics/bookpencil.gif For a text box to display scrollbars, its Multiline property must be set to true.

Change the ScrollBars property of your text box to Vertical and notice how scrollbars appear in the text box (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig06 Figure 7.6]).

Figure 7.6. If a text box may contain lots of text, give it a scrollbar.

graphics/07fig06.jpg

 Limiting the Number of Characters a User Can Enter 

You can limit the number of characters a user can type into a text box using the MaxLength property. All new text boxes are given the default value of 32767 for MaxLength, but you can change this as needed (up or down). Add a new text box to the form and set its properties as follows:

Property Value
Name txtRestrict
Location 128,80
MaxLength 10
Size 136,20
Text (make blank)

Run the project by pressing F5 and then enter the following text into the text box: So you run and you run. Be sure to try to enter more than 10 characters of text�you can't (if you can, you're probably entering the text into the text box with scrollbars, rather than into the new text box). All that you're allowed to enter is So you run (10 characters). The text box allows only 10 characters, whether that's via entry using the keyboard or a Paste operation. The MaxLength property is most often used when the text box's content is to be written to a database, in which field sizes are usually restricted (using a database is discussed in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch21.htm#ch21 Hour 21], "Working with a Database").

Stop the project by choosing Stop Debugging from the Debug menu and then click Save All on the toolbar.

 Creating Password Fields 

You've probably used a password field: a text box that displays an asterisk for each character entered. Any text box can be made a password field by assigning a character to its PasswordChar field. Select the PasswordChar property of the second text box now (txtRestrict) and enter an asterisk (*) for the property value. Run the project once more and enter text into the text box. Now an asterisk is displayed for each character you enter (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig07 Figure 7.7]). Although the user doesn't see the actual text contained in the text box, referencing the Text property in code always returns the true text.

Figure 7.7. A password field displays its password character for all entered text.

graphics/07fig07.jpg

graphics/bookpencil.gif A text box will display password characters only if its Multiline property is set to false.

Stop the project by choosing Stop Debugging from the Debug menu. Delete the asterisk from the PasswordChar field, and then save the project by clicking Save All on the toolbar.

Creating Buttons 

Every dialog box that Windows displays has at least one button on it. Buttons enable a user to invoke a function with a click of the mouse. Create a new project named Button Example, change the name of the default form to fclsButtonExample, set the form's Text property to Button Example, and update the entry point Main() to reference fclsButtonExample instead of Form1. Next, add a new button to the form by double-clicking the Button item in the toolbox. Set the button's properties as follows:

Property Value
Name btnClose
Location 104,90
Text Close

Add a new text box to the form and set its properties as follows:

Property Value
Name txtTest
Location 92,40
TabIndex 0
Text (make blank)

You're probably starting to see a pattern here. Whenever you add a new control to a form, the first thing you should do is give the control a descriptive name. If the control has a Text property, you should also change that to something meaningful. Your form should now look like [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig08 Figure 7.8].

Figure 7.8. Users click buttons, such as the Close button, to make things happen.

graphics/07fig08.jpg

There's no point in having a button that doesn't do anything, so double-click the button now to access its Click event, and then add the following statement:

this.Close();

Recall from [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch05.htm#ch05 Hour 5], "Building Forms�Part I," that this statement closes the current form. Because you'll have only one form in the project, this has the effect of terminating the application. Press F5 to run the project. The cursor appears in the text box, which means that the text box has the focus (it has the lowest TabIndex property). Press Enter and note that nothing happens (this will make sense shortly). Next, click the button and the form will close.

 Accept and Cancel Buttons 

When creating dialog boxes, it's common to assign one button as the default button (called the Accept button). If a form has an Accept button, that button's Click event is fired when the user presses Enter, regardless of which control has the focus. This is great for dialog boxes in which the user enters some text and presses Enter to commit the data and close the form. To designate a button as an Accept button, use the following steps:

  1. Select the AcceptButton property of the form.
  2. Look at the AcceptButton property of your form now�it reads (none). Click the property to select it and a drop-down arrow appears.
  3. Click the down arrow and you'll get a list of the buttons on the form (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig09 Figure 7.9]). Choose btnClose to make it the Accept button. Notice how the button now appears with a dark border, indicating that it is the Accept button.
Figure 7.9. You can designate only one button as a form's Accept button.

graphics/07fig09.jpg

  1. Press F5 to run the project. Again, the text box has the focus. Press Enter, and you'll find that the form closes. Again, pressing Enter on a form that has a designated Accept button causes that button's Click event to fire the same as if the user clicked it with the mouse, regardless of which control has the focus.

The Accept button is a useful concept, and you should take advantage of this functionality when possible. Keep in mind that when you do create an Accept button for a form, you should also create a Cancel button. A Cancel button is a button that fires its Click event when the user presses the Esc key, regardless of which control has the focus. Generally, you place code in a Cancel button to shut down the form without committing any changes made by the user. To designate a button as a Cancel button, choose it as the CancelButton property of the form.

 Adding a Picture to a Button 

Although it's not standard practice, and you shouldn't overuse the technique because doing so causes clutter and can reduce the usefulness of your interface, it's possible to add a picture to a button. The two primary methods of doing this are to add the picture to the button at design time by loading a picture into the Image property of the control using the Properties window, or to bind the button to an image list. I'll discuss loading a picture using the Properties window here and the Image List control in the next hour. (Note: You can load an image at runtime using the technique discussed for the Picture Viewer program in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch01.htm#ch01 Hour 1], "A C# Programming Tour.")

graphics/bookpencil.gif To perform this operation, you'll need a small bitmap. I've provided one at www.samspublishing.com called Close.bmp.

Select the button and display its properties in the Properties window. Click the Image property to select it, and then click the button with the three dots. The Open File dialog box is displayed, allowing you to find and select a bitmap. Use this dialog box to locate and select the Close.bmp bitmap or another small bitmap of your choosing. Click Open to load the image into the button's Image property, and the picture will appear on your button (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig10 Figure 7.10]).

Figure 7.10. The picture loaded into the Image property of a button appears on the button.

graphics/07fig10.jpg

graphics/bookpencil.gif Many controls have an Image property, and for the most part, they all work the same way as the Image property of the Button control.

Notice that there is a problem with how the picture appears on the button�the image overlays the text. This problem is easily corrected.

Although a picture is displayed in the center of a button by default, you can specify the placement using the ImageAlign property. Click the ImageAlign property to display a drop-down arrow, and then click the arrow. The drop-down list contains a special interface for specifying the alignment of the picture (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig11 Figure 7.11]). Each rectangle in the drop-down list corresponds to an alignment (center-left, center-center, center-right, and so on) Click the center-left rectangle now and the image will be moved to the left of the text. So much for problem one…

>

Creating Containers and Groups of Option Buttons

In this section, you'll learn how to create containers for groups of controls using panels and group boxes. You'll also learn how to use the Check Box and Option Button controls in conjunction with these container controls to present multiple choices to a user.

Begin by creating a new Windows Application titled Options. Change the name of the default form to fclsOptions and set the form's Text property to Options. Next, change the entry point Main() to reference fclsOptions instead of Form1.

 Using Panels and Group Boxes
graphics/newterm.gif Controls can be placed on a form because the form is a container object�an object that can contain controls. A form is not the only type of container, however. Some controls act as containers as well, and a container may host one or more other containers. The Panel and Group Box controls are both container controls that serve a similar purpose, yet each is more suited to a particular application.
graphics/bookpencil.gif The Panel control is a slimmed-down version of the Group Box control, so I won't be discussing it in depth. If you need a very basic container control without the additional features offered by the group box, such as a border and a caption, use the Panel control.

The group box is a container control with properties that let you create a border (frame) and caption. Add a new group box to your form now by double-clicking the GroupBox item in the toolbox. When you create a new group box, it has a border by default, and its caption is set to the name of the control (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig12 Figure 7.12]).

Figure 7.12. A group box acts like a form within a form.

graphics/07fig12.jpg

Set the properties of the group box as follows:

Property Value
Name grpMyGroupBox
Location 48,16
Size 200,168
Text This is a group box

The group box is a fairly straightforward control. Other than defining a border and displaying a caption, the purpose of a group box is to provide a container for other controls. The next two sections, "[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07lev2sec9 Presenting Yes/No Options Using Check Boxes]" and "[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07lev2sec10 Working with Radio Buttons]," help demonstrate the benefits of using a group box as a container.

 Presenting Yes/No Options Using Check Boxes 

The check box is used to display true/false values on a form. You're now going to add a check box to your form�but not in the way you have been adding other controls. As you know by now, double-clicking the CheckBox item in the toolbox will place a new Check Box control on the form. However, this time you're going to place the check box on the Group Box control.

To place a control on a group box, you can use one of the following techniques:

  • Add the control to the form, cut the control from the form, select the group box, and paste the control on the group box.
  • Draw the control directly on the group box.
  • Drop the control on the group box.

You're going to use the third method�dropping a new control directly on the group box. Follow these steps:

  1. Click the group box to select it.
  2. Click the CheckBox item in the toolbox and drag it to the group box.
  3. Release the mouse when you are over the group box.

You should now have a check box on your group box like the one shown in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig13 Figure 7.13].

Figure 7.13. Container controls hold other controls.

graphics/07fig13.jpg

Move the check box around by clicking and dragging it. You'll notice that you can't move the check box outside the group box's boundaries. This is because the check box is a child of the group box, not of the form. Set the properties of the check box as follows:

Property Value
Name chkMyCheckBox
Location 16,24
Size 120,24
Text This is a check box

When the user clicks the check box, it changes its visible state from checked to unchecked. To see this behavior, press F5 to run the project and click the check box a few times.

When you're done experimenting, stop the running project. To determine the state of the check box in code, use its Checked property. You can also set this property at design time using the Properties window.

 Working with Radio Buttons 

Check boxes are excellent controls for displaying true/false values. Check boxes work independently of one another, however. If you have five check boxes on a form, each of them could be checked or unchecked. Radio buttons, on the other hand, are mutually exclusive to the container on which they are placed. This means that only one radio button per container may be selected at a time. Selecting one radio button automatically deselects any other radio buttons on the same container. Radio buttons are used to offer a selection of items to a user when the user is allowed to select only one item. To better see how mutual exclusivity works, you're going to create a small group of radio buttons.

Click the RadioButton item in the toolbox to begin dragging, move the pointer over the group box, and then release the button to drop a new radio button on the group box. Set the properties of the radio button as follows:

Property Value
Name optOption1
Location 19,65
Size 104,24
Text This is option 1

You're going to copy this radio button and paste a copy of the control on the group box. Begin by right-clicking the radio button and choosing Copy from its context menu. Next, click the group box to select it, right-click the group box, and choose Paste from its context menu to create a new radio button. Set the properties of the radio button as follows:

Property Value
Name optOption2
Checked true
Location 19,96
Text This is option 2

Now that you have your two radio buttons (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig14 Figure 7.14]), run the project by pressing F5.

Figure 7.14. Radio buttons restrict a user to selecting a single item.

graphics/07fig14.jpg

Click the first radio button to select it, and notice how the second radio button becomes deselected automatically (its Checked property is set to false). Two radio buttons are sufficient to demonstrate the mutual exclusivity, but be aware that you could add as many radio buttons to the group box as you care to and the behavior would be the same. The important thing to remember is that mutual exclusivity is shared only by radio buttons placed on the same container. To create radio buttons that behave independently of one another, you would need to create a second set. You could easily create a new group box (or panel for that matter) and place the second set of radio buttons on the new container. The two sets of radio buttons would behave independently of one another, but mutual exclusivity would still exist among the buttons within each set.

Stop the running project and save your work.

>

Displaying a List with the List Box

The 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 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 because of the size of the control, scrollbars are automatically displayed.

graphics/bookpencil.gif 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 lists 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. In the next section, I'll discuss features specific to the combo box.

Create a new project titled Lists. Change the name of the default form to fclsLists and set its Text property to Lists Example. Next, change the entry point Main() to reference fclsLists instead of Form1. Set the form's Size property to 300,320. Add a new list box control to the form by double-clicking the ListBox item in the toolbox. Set the properties of the list box as follows:

Property Value
Name lstPinkFloydAlbums
Location 72,32
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. Most often, you'll manipulate the Items collection using code (which I'll show you a little bit later in this hour), but you can also work with the collection at design time 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 box�one item to a line.

Enter the following items:

  • Atom Heart Mother
  • Saucer Full of Secrets
  • Wish You Were Here
  • Animals
  • Echoes
  • Piper at the Gates of Dawn

When you're finished, your screen should look like that shown in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig15 Figure 7.15]. Click OK to commit your entries and close the window. Notice that the list box contains the items that you entered.

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

graphics/07fig15.jpg

 Manipulating Items at Runtime 

In [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03.htm#ch03 Hour 3], "Understanding Objects and Collections," you learned all 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) is an object property that returns a collection (collections in many ways are like objects�they have properties and methods). To manipulate list items, you manipulate the Items collection.

graphics/bookpencil.gif Whether you choose to set values at design time or runtime depends on the situation. For example, if you don't know the values at design time, you'll have to set them at runtime. I recommend that you set values at design-time whenever possible.

A list may contain duplicate values, as you'll see in this example. Because of this, C# needs another mechanism to treat each item in a list as a unique item. 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 collection, not the top item visible in the list.

 Adding Items to a List 

New items are added to the Items collection using the Add method of the 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 104,160
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 argument�the text to add to the list.

graphics/bookpencil.gif Unlike items added at design time, items added through code aren't preserved when the program is ended.

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");

Stop the running project and save your work before continuing.

graphics/bulb.gif 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 instance, 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 will remove an item from the list. Create a new button and set its properties as follows:

Property Value
Name btnRemoveItem
Location 104,192
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 C# to search the Items collection, starting at the first item (index = 0), and when an item is found that matches the specified text, to remove that item. As I stated earlier, you can have multiple items with the same text. The Remove method will remove only the first occurrence; after the text is found and removed, C# stops looking. Press F5 to run the project now. Click the Add an Item button a few times to add Dark Side of the Moon to the list (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig16 Figure 7.16]). Next, click the Remove an Item button and notice how C# finds and removes one instance of the item.

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

graphics/07fig16.jpg

graphics/bookpencil.gif To remove an item at a specific index, use the RemoveAt method. For instance, to remove the first item in the list, you could use a statement such as 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 are now going to add a button to the form that will clear the list when clicked. Add a new button to the form now and set the button's properties as follows:

Property Value
Name btnClearList
Location 104,224
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 if 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.

graphics/bulb.gif Remember, 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 get 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 

By default, a list box allows only a single item to be selected by the user at one time. Whether a list allows multiple selections is determined by the SelectionMode property of the list box. You will need to understand how to work with the selected item in a list box that allows only a single selection (list boxes that allow multiple selections are more complex and are beyond the scope of the book).

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, an empty string is returned. At times, it's desirable to know the index of the selected item. This is returned by 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 a �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 the Output window. First, change the Height property of the form to 320 to accommodate one more button. As you build your interfaces, you'll often have to make small tweaks such as this because it's nearly impossible to anticipate everything ahead of time. Add a new button to the form and set its properties as follows:

Property Value
Name btnShowItem
Location 104,256
Size 96,23
Text Show Selected

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

System.Diagnostics.Debug.WriteLine(lstPinkFloydAlbums.SelectedItem);
System.Diagnostics.Debug.WriteLine(lstPinkFloydAlbums.SelectedIndex);
graphics/bookpencil.gif System.Diagnostics.Debug.WriteLine sends text to the Output window. If you are planning to write several debug statements, it may be helpful to declare the System.Diagnostics namespace at the beginning of your class. This permits you to use the methods of the namespace without having to qualify the entire namespace. For example, after the namespace System.Diagnostics is declared in the class, you could use a statement like the following:
Debug.WriteLine(lstPinkFloydAlbums.SelectedItem);<br />

Notice how you don't have to reference System.Diagnostics on this line; the compiler is able to determine this automatically.

To specify a namespace so that you can reference its objects without explicitly referencing the namespace, you add a using statement in the header of the class file (with the other using statements that C# automatically places in the header). For example, to reference the System.Diagnostics namespace, you could add a statement like this to the class's header:

using System.Diagnostics;<br />

Again, after you've added the namespace with a using statement, you can reference the namespace's objects without explicitly referencing System.Diagnostics, as seen next:

Debug.WriteLine(lstPinkFloydAlbums.SelectedItem);<br />Debug.WriteLine(lstPinkFloydAlbums.SelectedIndex);<br />

Press F5 to run the project and click the Show Selected button. Take a look at the Output window. You'll see a blank line (the empty string returned by SelectedItem) and a �1, returned by SelectedIndex denoting that no item 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 Output window (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig17 Figure 7.17]).

Figure 7.17. The SelectedItem and SelectedIndex properties make it easy to determine which item is selected.

graphics/07fig17.jpg

Stop the running project and save your work.

 Sorting a List 

List boxes and combo boxes have a Sorted property. By default, this property is set to false. Changing this property value to true causes 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 member. You don't have to call Sorted to sort the contents of a list. Instead, as long as the Sorted property is set to true, C# enforces a sort order. This means that all items added using the Add method are automatically inserted into the proper location, in contrast to being inserted at the end of the list, which is the behavior of an unsorted list.

Creating Drop-Down Lists Using the Combo Box 

List boxes are great, but they have two shortcomings. First, they take up quite a bit of space. Second, users can't enter their own values; they have to select from the items in the list. If you need to conserve space or if you want to allow a user to enter a value that may not exist in the list, use the Combo Box control.

Combo boxes have an Items collection that behaves exactly like that of the List Box control (refer to the previous section for information on manipulating lists). Here I will show you the basics of how a combo box works.

Add a new combo box to the form by double-clicking the ComboBox item in the toolbox. Set the combo box's properties as follows:

Property Value
Name cboColors
Location 72,8
Size 160,21
Text (make blank)

The first thing you should note is that the combo box has a Text property, whereas the list box doesn't. This works the same as the Text property of a text box. When the user selects an item from the drop-down list, the value of the selected item is placed in the Text property of the text box. The default behavior of a combo box is to allow the user to enter any text in the text box portion of the control�even if the text doesn't exist in the list. Shortly, I'll show you how to change this behavior.

Select the Items property of the combo box in the Properties window and click the button that appears. Add the following items to the String Collection editor and click OK to commit your entries.

  • Black
  • Blue
  • Gold
  • Green
  • Red
  • Yellow

Press F5 to run the project. Click the arrow at the right side of the combo box and a drop-down list appears (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#ch07fig18 Figure 7.18]).

Figure 7.18. Combo boxes conserve space.

graphics/07fig18.jpg

Next, try typing in the text Magenta. C# lets you do this. Indeed, you can type any text that you desire. Often, you'll want to restrict a user to entering only values that appear in the list. To do this, you change the DropDownStyle property of the combo box. Close the form to stop the running project and change the DropDownStyle property of the combo box to DropDownList. Press F5 to run the project again and try to type text into the combo box. You can't. However, if you enter a character that is the start of a list item, C# will select the closest matching entry.

As a matter of fact, clicking in the "text box" portion of the combo box opens the list the same as if you clicked the drop-down arrow. When set as a DropDownList, a combo box won't allow any text entry; therefore, the user is limited to selecting items from the list.

Stop the running project now and save your work. As you can see, the combo box and list box offer similar functionality. In fact, the coding of their lists is identical. However, each one of these controls serves a slightly different purpose. Which one is better? That depends entirely on the situation. As you use professional applications, pay attention to their interfaces; you'll start to get a feel for which control is appropriate in a given situation.

Summary 

In this hour you learned how to present text to a user. You learned that the Label control is perfect for displaying static text (text the user can't enter) and that the text box is the control to use for displaying edited text. You can now create text boxes that contain many lines of text, and you know how to add scrollbars when the text is greater than what can be displayed in the control.

I don't think I've ever seen a form without at least one button on it. You've now learned how to add buttons to your forms and how to do some interesting things, such as adding a picture to a button. For the most part, working with buttons is a simple matter of adding one to a form, settings its Name and Text properties, and adding some code to its Click event�all of which you now know how to do.

Check boxes and option buttons are used to present true/false and mutually exclusive options, respectively. In this hour, you learned how to use each of these controls and how to use group boxes to logically group sets of related controls.

Last, you learned how to use list boxes and combo boxes to present lists of items to a user. You now know how to add items to a list at design time as well as runtime, and you know how to sort items. The List Box and Combo Box are powerful controls, and I encourage you to dig deeper into the functionality they possess.

Without controls, users would have nothing to interact with on your forms. In this hour, you learned how to use the standard controls to begin building functional interfaces. Keep in mind that I only scratched the surface of each of these controls and that most do far more than I've hinted at here. Mastering these controls will be easy for you, as you'll be using them a lot.

>

Q&A

[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#qad1e25275 Q1:] Can I place radio buttons directly on a form?
A1: Yes. The form is a container, so all radio buttons placed on a form are mutually exclusive to one another. If you wanted to add a second set of mutually exclusive buttons, they'd have to be placed on a container control. In general, I think it's best to place radio buttons on a group box rather than on a form because the group box provides a border and a caption for the radio buttons and makes it much easier to move the set of radio buttons around when you're designing the form.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/07.htm#qad1e25285 Q2:] I've seen what appears to be list boxes that have a check box next to each item in the list. Is this possible?
A2: Yes. In C#, this is accomplished using an entirely different control: the checked list box.

Workshop

The Workshop is designed to help you anticipate possible questions, review what you've learned, and get you thinking about how to put your knowledge into practice. The answers to the quiz are in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01.htm#app01 Appendix A],"Answers to Quizzes/Exercises."

 Quiz
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec7.htm#ch07ans01 1:] Which control would you use to display text that the user can't edit?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec7.htm#ch07ans02 2:] What common property is shared by the Label control and text box 2and whose value determines what the user sees in the control?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec7.htm#ch07ans03 3:] To change the Height of a text box, you must set what property?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec7.htm#ch07ans04 4:] What is the default event of a Button control?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec7.htm#ch07ans05 5:] A button whose Click event is triggered when the user presses Enter, regardless of the control that has the focus, is called an…?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec7.htm#ch07ans06 6:] Which control would you use to display a yes/no value to a user?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec7.htm#ch07ans07 7:] How would you create two distinct sets of mutually exclusive option buttons?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec7.htm#ch07ans08 8:] To manipulate items in a list, you use what collection?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec7.htm#ch07ans09 9:] What method adds an item to a list in a specific location?
Exercises
  1. Create a form with a text box and a combo box. Add a button that, when clicked, adds the contents of the text box to the combo box.
  2. Create a form with two list boxes. Add a number of items to one list box at design time using the Properties window. Create a button that, when clicked, removes the selected item in the first list and adds it to the second list.