






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







♦ Chapter Overview
♦ Chapter Objectives
♦ Instructor Notes
♦ Quick Quizzes
♦ Discussion Questions
♦ Projects to Assign
♦ Key Terms
Chapter Overview
In this chapter, the focus is on adding controls to Windows applications and programming their events. Applications that have menus and other widgets that can be displayed and responded to, such as list boxes, radio buttons, combo boxes, and check boxes, are created. Additional event- handling methods for capturing and responding to user input are introduced.
Chapter Objectives
In this chapter, students will:
Instructor Notes
Delegates are special types of .NET classes whose instances store references (addresses) to methods. Delegates form the foundation for events in C#. They are used in applications other than Windows applications that respond to GUI events; however, it is their relationship to events that makes them interesting.
Defining Delegates The declaration for a delegate looks more like a method declaration than a class definition. But, it has no body. It begins with the keyword delegate. It ends with a parenthesized list of parameters followed by a semicolon. Every delegate type has a signature, which may include zero or more parameters. Remember that a signature for a method includes its name, number of parameters, and parameter types. The signature of a method does not include the return type. Like methods, a delegate may include a return type or the keyword void as part of its heading. However, unlike a method, the return type of a delegate becomes part of its identifying signature. When you define a delegate type, you identify what types of methods the delegate represents.
program when you double-clicked on a Button control object during design (or selected its click event from the Event list in the Properties window). The event was registered as being of interest, and an event-handler method heading was generated by Visual Studio.
When Visual Studio adds the event-handler method heading, the body of the method is empty. You add the program statements to the body of the method, indicating what actions to perform when the button is clicked.
Event-Handler Methods A delegate maintains a list of the registered event handlers for an event. Because of using this delegate, all event-handler methods have the same signature. They have a return type of void with two parameters. The first parameter, object sender, represents the source that raises the event, and the second parameter represents the data for the event.
Quick Quiz
ListBox controls are used to display a list of items. Both single and multiple selections can be made. When the total number of items exceeds the number that can be displayed in the size box selected, a scroll bar is automatically added to the control. Items can be added or removed to and from at run time.
Create a Form to Hold ListBox Controls To experience working with a ListBox object, a new project is created in Visual Studio using the Windows application template. BackColor, Text, and Font properties are set. TextBox and Label objects are dragged to the form.
Adding a ListBox Control Object A ListBox object is dragged onto the form. Its Name, BackColor, ForeColor, and Sorted properties are set. The Items property is used to set the initial values for the list box. Clicking on the button with the ellipsis to the right of the word Collection in the Items property displays
the String Collection Editor window. Values for the list box are typed on separate lines using this editor.
Register a ListBox Event To add functionality, an event is registered so that when the item selection changes in the ListBox, the new selection is displayed. Double-clicking on the ListBox control wires an event handler to it. An empty-bodied method is created for the listBox1_SelectedIndexChanged( ).
ListBox Event Handlers The SelectedItem property returns an object representing selection. In order to display the selection in a TextBox, it must be converted to a string.
Multiple Selections with a ListBox Object The SelectionMode property has selection values of MultiSimple, MultiExtended, None, and One. By default, the property is set to One. With MultiExtended, users can make multiple selections using the Ctrl and Shift keys in the way that standard multi-selections are done with Windows. Multiple selections can also be made using arrow keys, Spacebar, and mouse clicks. With MultiSimple, multiple selections are made by using the Spacebar and clicking the mouse.
Inside the listBoxEvents_SelectedIndexChanged( ) method, a foreach is used to concatenate selections one item at a time onto a string instance named result. On the outside of the loop, the concatenated string for result is placed in the text box.
It is important to note that each time a new selection is clicked, the event is fired. If three items are selected, the event handler method is executed three times. Inside the event handler method, notice that the result string is reinitialized (result = “ “). The for statement (activity in lstBoxEvents.SelectedItems) appends those SelectedItems onto the string.
Adding Items to a ListBox at Run Time ListBox object can hold data of any type. Values returned using the SelectedItem and SelectedItems properties are returned as objects; thus, they normally must be cast or converted to another type for processing. To add a value when the program is running, you use the Add( ) method with the Items property. Items, SelectedItems, and SelectedIndices properties are useful for getting a collection of selected items from the ListBox object. Review Tables 10- and 10-3 for a list of ListBox properties and methods.
Quick Quiz
Using Collection Indexes When you want to retrieve multiple selections from a ListBox object, the Text property cannot be used. Text gets the first one selected. To retrieve all of the choices, you can use the SelectedItems, SelectedIndices, or Items methods. The collections are zero-based structures. For example, SelectedIndices is a collection of indexes. Once the selections are retrieved, you can access them like you access the elements in an array.
Quick Quiz
Offer the advantage of enabling the addition of a lot of functionality while taking up minimal space.
Adding Menus It is easy to drag and drop a MenuStrip control object to a Windows form. To add the text for the menu option, select this MenuStrip icon (from the component tray) and then click on the form in the top-left corner, where the menu should display. When the menu structure displays, type the text. Moving to the right or below the current text box selection enables you to type either a subordinate menu option (below it) or another top-level menu option to the right.
When you type the text that is to appear in the menu, preceding a character with an ampersand (&) places an underline under the next character typed so that it can be used as a shortcut when used in combination with the Alt key. A special Shortcut property for menu items exists. You can set other shortcuts using the Properties window. Select Insert Separator from the pop-up menu.
The MenuStrip control is a newer menu option. Another option for adding menus is to use the MainMenu control, which was available in earlier versions. If you use the MainMenu control, you must set the Menu property on the form to the name of the MainMenu object. Otherwise, the menu does not display when you launch the application.
Set the Name property for each menu option so that the menu item can be wired to an event with an appropriate name. The name becomes part of the event-handler method. If you name a menu option after wiring its event handler to the menu option, the event-handler method name does not carry the name of the control.
Adding Predefined Standard Windows Dialog Boxes There are a number of preconfigured dialog boxes. They include boxes that look like the standard Windows File Open, File Save, File Print, File Print Preview, Format Font, and Format Color dialog boxes. They are added to your application by dragging and dropping the control object on your form.
For the menuFont_Click( ) and menuColor_Click( ) methods, you can retrieve or set the current Font or Color setting from the an object using the Font and ForeColor properties. Example 10- 20 illustrates wiring and programmed Click( ), KeyPress( ), CheckedChanged( ), menuFont_Click( ), menuColor_Click( ), menuAbout( ), and SelectedIndexChanged( ) events. Table 10-4 lists the properties that are changed for the application.
Remember that three separate source code files are now created for each Windows application. The Main( ) method is stored in the file, which has a default name of Program.cs. The second and third files have partial class designations. The xxxxx.Designer.cs stores all the Visual Studio generated code used to instantiate objects that were dragged and dropped onto the form. Developer code is added to the other file (xxxxx.cs).
Quick Quiz
These objects are often grouped together, but they differ in appearance and functionality.
Quick Quiz
Another option for creating Windows applications is to use Windows Presentation Foundation (WPF) as opposed to WinForms. The interface for Visual Studio 2010 was built using WPF. As with WinForms application, you can drag and drop controls from the Toolbox onto the window. Property values can be set and events registered, but there is not a one-to-one correspondence between properties with WinForms and properties with WPF. Encourage students to explore them.
WPF applications create eXtensible Application Markup Language files, which resemble Hypertext Markup Language (HTML) files, complete with beginning and ending tags. A WPF XAML file is like an HTML file for Windows applications. You do not find the objects, like RadioButtons, instantiated. There is no .designer.cs file. Objects like textboxes and labels are described in the XAML file. There is still the code behind file found with WPF applications. This is the main feature that WinForms and WPF applications share in common.
A TabControl object displays multiple tabs, like dividers in a notebook or labels in a set of folders in a filing cabinet. This control makes it possible to create a multiple-page dialog. You can place pictures, buttons, labels, or any control on each tabbed page. Add a TabControl object to the page by dragging the control from the Container section of the Toolbox onto your blank form. Two tabs are included by default. You can stretch the control to cover the form. To format individual tabs, the TabPages property is used. Clicking the ellipsis beside the Collection value on the TabPages property displays the TabPages Collection Editor, where each tab has its own set of properties that can be set.
Quick Quiz
This application demonstrates event-driven applications by creating a graphical user interface for a Windows application. An application for an on-campus diner is designed that accepts food and drink selections as input. The GUI provides options for showing the total cost of the order, displaying the current order selections, or allowing users to change their minds about each of the selections. The interface should enable special requests to be entered.
Two classes are constructed to separate the business logic from the presentation details. The first class defines a template for a food order object. It includes behaviors for processing an order that includes selections for entrée, drink, and special requests. The class assigns prices to each item selected and determines the overall price of the order.
The second class is created for the user interface. It instantiates an object of the Order class and instantiates a Windows Form object to represent the graphical user interface. Using the .NET predefined Control classes, Label, ComboBox, ListBox, RadioButton, CheckBox, and Menu objects are added to the Form object.
Structured English (pseudocode) and class diagrams are included with the example. A prototype for the desired output is shown. Tables are shown documenting the properties that were set during design. The complete program listing is shown in the book and is available as a Visual Studio project to demo for the class.
Encourage students to name controls before registering events.