C# Programming: From Problem Analysis to Program Design Programming Based on Events 10 C# Programming: From Problem Analysis to Program Design 5th Edition C# Programming: From Problem Analysis to Program Design
Chapter Objectives Define, create, and use delegates and examine their relationship to events Explore event-handling procedures in C# by writing and registering event-handler methods Create applications that use the ListBox control object to enable multiple selections from a single control Contrast ComboBox to ListBox objects by adding both types of controls to an application C# Programming: From Problem Analysis to Program Design
Chapter Objectives (continued) Add Menu and TabControl control options to Window forms and program their event-handler methods Wire multiple RadioButton and CheckBox object events to a single event-handler method Design and create a Windows Presentation Foundation (WPF) application Work through a programming example that illustrates the chapter’s concepts C# Programming: From Problem Analysis to Program Design
Delegates Delegates form the foundation for events in C# Delegates store references (addresses) to methods For events, it is the address of which method to invoke when an event is fired Delegates enable you to pass methods as arguments (as opposed to data) to other methods Delegate signature Identifies what types of methods the delegate represents C# Programming: From Problem Analysis to Program Design
Delegates (continued) Declaration for a delegate looks more like a method declaration than a class definition Except, delegate declaration has no body Declaration begins with the keyword delegate Declaration ends with a parenthesized list of parameters Unlike a method, the return type of a delegate becomes part of its identifying signature Recall signature for method includes only the name and the number and type of parameters – not the return type C# Programming: From Problem Analysis to Program Design
Defining Delegates Delegate declaration example delegate string ReturnsSimpleString( ); Above example represents methods that return a string and require no argument Given the signature, the following methods could be associated or referenced by the delegate static string EndStatement( ) static string ToString( ) static string ReturnSaying( ) C# Programming: From Problem Analysis to Program Design
Creating Delegate Instances Think of the delegate as a way of defining or naming a method signature Associate delegate with method(s) by creating delegate instance(s) ReturnsSimpleString saying3 = new ReturnsSimpleString(EndStatement); Constructor for delegate of the delegate class always takes just parameter (method name) Name of a method for the constructor to reference C# Programming: From Problem Analysis to Program Design
Using Delegates Delegate identifier references the method sent as argument to constructor Any use of delegate identifier now calls that method Methods are said to be wrapped by the delegate Delegate can wrap more than one method, called a multicast delegate += and -= operators are used to add/remove methods to/ from the delegate chain or invocation list Multicast delegates must have a return type of void C# Programming: From Problem Analysis to Program Design
Using Delegates (continued) delegate string ReturnsSimpleString( ); static void Main ( ) { int age = 18; ReturnsSimpleString saying1 = new ReturnsSimpleString(AHeading); ReturnsSimpleString saying2 = new ReturnsSimpleString((age + 10).ToString); ReturnsSimpleString saying3= new ReturnsSimpleString(EndStatement); MessageBox.Show(saying1( ) + saying2( ) + saying3( )); } C# Programming: From Problem Analysis to Program Design
Using Delegates (continued) These methods were associated (referenced) by the ReturnsSimpleString ( ) delegate // Method that returns a string. static string AHeading() { return "Your age will be "; } static string EndStatement( ) return " in 10 years."; C# Programming: From Problem Analysis to Program Design
Using Delegates (continued) Review DelegateExample C# Programming: From Problem Analysis to Program Design
Relationship of Delegates to Events Delegate acts as intermediary between objects that are raising or triggering an event During compilation, the method or methods that will be called are not determined Events are special forms of delegates Place a reference to event-handler methods inside a delegate Once reference is made, or event is registered, delegate is used to call event-handler method when an event like a button click is fired C# Programming: From Problem Analysis to Program Design
Event Handling in C# Form Designer in Visual Studio did much of the work for you Double-clicked on a Button control object during design 1) Click event is registered as being of interest 2) An event-handler method heading is generated Two steps form event wiring process Wire an event: associate (identify) a method to handle its event C# Programming: From Problem Analysis to Program Design
Event-Handler Methods Code associates the methods with a delegate this.button1.Click += new System.EventHandler(this.button1_Click); this.button2.Click += new System.EventHandler(this.button2_Click); System.EventHandler is a delegate type button1.Click and button2.Click are methods Keyword this is added to all code generated by Visual Studio to indicate the current instance of a class C# Programming: From Problem Analysis to Program Design
ListBox Control Objects Displays list of items for single or multiple selections Scroll bar is automatically added when total number of items exceeds the number that can be displayed Can add or remove items at design time or dynamically at run time C# Programming: From Problem Analysis to Program Design
ListBox Control Includes number of properties and events Items property Used to set initial values Click on (Collections) to add items Name property Useful to set if you are going to write program statements to manipulate the control Sorted property Set to true to avoid having to type values in sorted order C# Programming: From Problem Analysis to Program Design
ListBox Control Properties Table 10-2 ListBox properties C# Programming: From Problem Analysis to Program Design
Adding a ListBox Control Object Add ListBox control, then click on Items property (Collection) to type entries C# Programming: From Problem Analysis to Program Design
ListBox Control Methods Events are methods….Default event for ListBox Table 10-3 ListBox methods C# Programming: From Problem Analysis to Program Design
Registering A ListBox Event Might want to know when the item selection changes Double-clicking on any control registers its default event for the control SelectedIndexChanged( ) → default event for ListBox C# Programming: From Problem Analysis to Program Design
ListBox Event Handlers Register its event with the System.EventHandler delegate this.lstBoxEvents.SelectedIndexChanged += new System.EventHandler (this.listBox1_SelectedIndexChanged); Visual Studio adds event-handler method private void listBox1_SelectedIndexChanged (object sender, System.EventArgs e) { } C# Programming: From Problem Analysis to Program Design
ListBox Control Objects To retrieve string data from ListBox, use Text property this.txtBoxResult.Text = this.lstBoxEvents.Text; Place in method body When event fires, selection retrieved and stored in TextBox object C# Programming: From Problem Analysis to Program Design
ListBox Control Objects (continued) C# Programming: From Problem Analysis to Program Design
Multiple Selections with a ListBox SelectionMode Property has values of MultiSimple, MultiExtended, None, and One MultiSimple: use the spacebar and click the mouse MultiExtended can also use Ctrl key, Shift key, and arrow keys foreach(string activity in lstBoxEvents.SelectedItems) { result += activity + " "; } this.txtBoxResult.Text = result; C# Programming: From Problem Analysis to Program Design
ListBox Control Objects (continued) C# Programming: From Problem Analysis to Program Design
ListBox Control Objects (continued) SelectedItem and SelectedItems return objects Store numbers in the ListBox, once retrieved as objects, cast the object into an int or double for processing C# Programming: From Problem Analysis to Program Design
Adding Items to a ListBox Add items at run time using Add( ) method with the Items property lstBoxEvents.Items.Add("string value to add"); private void btnNew_Click(object sender, System.EventArgs e) { lstBoxEvents.Items.Add(txtBoxNewAct.Text); } C# Programming: From Problem Analysis to Program Design
ListBoxExample C# Programming: From Problem Analysis to Program Design
Review ListBoxExample private void lstBxEvents_SelectedIndexChanged (object sender, EventArgs e) { string result = " "; foreach (string activity in lstBxEvents.SelectedItems) result += activity + " "; this.txtBxResult.Text = result; } Review ListBoxExample C# Programming: From Problem Analysis to Program Design
ListBoxExample (continued) Table 10-1 ListBoxExample property values C# Programming: From Problem Analysis to Program Design
ListBoxExample (continued) Table 10-1 ListBoxExample property values (continued) C# Programming: From Problem Analysis to Program Design
ComboBox Objects In many cases, ListBox and ComboBox controls can be used interchangeably ListBox control is usually used when you have all the choices available at design time ComboBox facilitates displaying a list of suggested choices with an added feature ComboBox objects contain their own text box field as part of the object C# Programming: From Problem Analysis to Program Design
GardeningForm Example New Project created Includes ListBox and ComboBox Objects Create Project like previous ones Add Label Change property values for form Drag and drop ComboBox and ListBox onto form C# Programming: From Problem Analysis to Program Design
Programming Event Handlers For ListBox, use SelectedItems, SelectedIndices, or Items to retrieve a collection of items selected Zero-based structures Access them as you would access an element from an array SelectedIndices is a collection of indexes Text ONLY gets the first one selected C# Programming: From Problem Analysis to Program Design
Adding ComboBox Controls Extra TextBox object with ComboBox – User selects from list or types new value C# Programming: From Problem Analysis to Program Design
Adding ComboBox Controls (continued) Top line left blank in ComboBox when DropDownStyle property is set to DropDown (default setting) C# Programming: From Problem Analysis to Program Design
This line gets added to .designer.cs ComboBox Double clicking on ComboBox object registers it’s default event (SelectedIndexChanged( ) this.cmboFlowers.SelectedIndexChanged += new System.EventHandler(this.cmboFlowers_SelectedIndexChanged); this.txtBxResultFlowers.Text = this.cmboFlowers.Text; This line gets added to .designer.cs Use .Text property to retrieve the value C# Programming: From Problem Analysis to Program Design
Handling ComboBox Events ComboBox only allows a single selection to be made ListBox allows multiple selections Default event-handler method: SelectedIndexChanged( ) Same as ListBox control object Could register TextChanged( ) event Method is executed when new values are entered C# Programming: From Problem Analysis to Program Design
Programming Event Handlers (continued) C# Programming: From Problem Analysis to Program Design
MenuStrip Controls Offers advantage of taking up minimal space Drag and drop MenuStrip object from toolbox to your form Icon representing MenuStrip placed in Component Tray Select MenuStrip object to set its properties To add the text for a menu option, select the MenuStrip icon and then click in the upper-left corner of the form C# Programming: From Problem Analysis to Program Design
Adding Menus Drag MenuStrip control to form, then click here to display Menu structure C# Programming: From Problem Analysis to Program Design
MenuStrip Control Objects Ampersand (&) is typed between the F and o for the Format option to make Alt+o shortcut for Format C# Programming: From Problem Analysis to Program Design
MenuStrip Control Objects (continued) To create separators, right-click on the text label (below the needed separator) Select Insert Separator C# Programming: From Problem Analysis to Program Design
Menu To add tool tip, drag ToolTip control from Toolbox anywhere on the form ToolTip, like MenuStrip rest in Component Tray below design surface Separate ToolStripMenuItem objects are created from each selectable menu option Each has its own properties Each can have its own even handler method C# Programming: From Problem Analysis to Program Design
MenuStrip Control Objects (continued) ToolTip property sets text that’s displayed when the cursor is rested on top of the control C# Programming: From Problem Analysis to Program Design
Wire Methods to Menu Option Event Set the Name property for each menu option Do this first, then wire the event Click events are registered by double-clicking on the Menu option When the menu option is clicked, the event triggers, happens, or is fired C# Programming: From Problem Analysis to Program Design
Menu Event Handler Methods private void menuExit_Click(object sender, System.EventArgs e) { Application.Exit( ); } private void menuAbout_Click(object sender, System.EventArgs e) MessageBox.Show("Gardening Guide Application\n\n\nVersion" + " 1.0", "About Gardening"); C# Programming: From Problem Analysis to Program Design
Adding Predefined Standard Windows Dialog Boxes Included as part of .NET Dialog boxes that look like standard Windows dialog boxes File Open, File Save, File Print, and File Print Preview Format Font Format Color dialogs C# Programming: From Problem Analysis to Program Design
Adding Predefined Standard Windows Dialog Boxes C# Programming: From Problem Analysis to Program Design
Adding Predefined Standard Windows Dialog Boxes – Font private void menuFont_Click (object sender, System.EventArgs e) { fontDialog1.Font = lblOutput.Font; if (fontDialog1.ShowDialog( ) != DialogResult.Cancel ) lblOutput.Font = fontDialog1.Font ; } C# Programming: From Problem Analysis to Program Design
Adding Predefined Standard Windows Dialog Boxes – Color Retrieves the current ForeColor property setting for the Label object private void menuColor_Click(object sender, System.EventArgs e) { colorDialog1.Color = lblOutput.ForeColor; if (colorDialog1.ShowDialog( ) != DialogResult.Cancel ) lblOutput.ForeColor = colorDialog1.Color; } Checks to see if Cancel button clicked Set to selection made C# Programming: From Problem Analysis to Program Design
Adding Predefined Standard Windows Dialog Boxes – Color C# Programming: From Problem Analysis to Program Design
Review GardeningForm Example GardeningForm App Three separate source code files are created for this Windows application with ListBox and ComboBox One file has Main( ) method – default name Program.cs No changes made to this file Other two files’ headings include partial class definition .Designer.cs file has all autogenerated code from dragging and dropping controls and changing property values .cs file has event handler methods Review GardeningForm Example C# Programming: From Problem Analysis to Program Design
GardeningForm Properties Each entry has an associated statement in the .Designer.cs file Table 10-4 GardeningForm property values C# Programming: From Problem Analysis to Program Design
GardeningForm Properties (continued) Table 10-4 GardeningForm property values (continued) C# Programming: From Problem Analysis to Program Design
GardeningForm Properties (continued) Table 10-4 GardeningForm property values (continued) C# Programming: From Problem Analysis to Program Design
GardeningForm Properties (continued) Table 10-4 GardeningForm property values (continued) C# Programming: From Problem Analysis to Program Design
GardeningForm Events Table 10-5 GardeningForm events C# Programming: From Problem Analysis to Program Design
CheckBox and RadioButton Objects New Project is created Windows Application CheckBox and RadioButton objects added like other objects Drag and drop controls Set BackColor properties Set Title bar using Text property Name controls C# Programming: From Problem Analysis to Program Design
CheckBox Objects Appear as small boxes Allow users to make a yes/no or true/false selection Checked property set to either true or false depending on whether a check mark appears or not Default false value CheckChanged( ) – default event-handler method Fired when CheckBox object states change Can wire one event handler to multiple objects C# Programming: From Problem Analysis to Program Design
Wiring One Event Handler to Multiple Objects Using Properties window, click on the Events Icon Click the down arrow associated with that event Select method to handle the event Follow the same steps for other objects C# Programming: From Problem Analysis to Program Design
Method name more generic so it can be used with multiple controls CheckBox Control Originally default event handler method for the Swim CheckBox object was: private void ckBxSwim_CheckedChanged (object sender, System.EventArgs e) { } The heading for ckBxSwim_CheckedChanged( ) changed to ComputeCost_CheckedChanged ( ) private void ComputeCost_CheckedChanged (object sender, System.EventArgs e) { } Method name more generic so it can be used with multiple controls C# Programming: From Problem Analysis to Program Design
GroupBox Objects GroupBox provides an identifiable group for controls – gives you a heading Objects may be grouped together for visual appearance Can move or set properties that impact the entire group GroupBox control should be placed on the form before you add objects GroupBox control adds functionality to RadioButton objects Allow only one selection C# Programming: From Problem Analysis to Program Design
RadioButton Objects Appear as small circles Give users a choice between two or more options Not appropriate to select more than one RadioButton object (from a group) Group RadioButton objects by placing them on a Panel or GroupBox control Setting the Text property for the GroupBox adds a labeled heading over the group C# Programming: From Problem Analysis to Program Design
Adding RadioButton Objects Box drawn around RadioButton objects is from GroupBox C# Programming: From Problem Analysis to Program Design
RadioButton Objects (continued) Turn selection on this.radInterm.Checked = true; Raise a number of events, including Click( ) and CheckedChanged( ) events Wire the event-handler methods for RadioButton objects, just like CheckBox C# Programming: From Problem Analysis to Program Design
Wiring One Event Handler to Multiple Objects (continued) Each CheckBox and RadioButton wired to same method C# Programming: From Problem Analysis to Program Design
RadioButton Objects (continued) ComputeCost_CheckedChanged( ) method if (this.radBeginner.Checked) { cost +=10; this.lblMsg.Text = "Beginner " + "-- Extra $10 charge"; } else // more statements Review RegistrationApp Example C# Programming: From Problem Analysis to Program Design
ComputeCost_CheckChanged( ) and Click( ) Events Raised C# Programming: From Problem Analysis to Program Design
Windows Presentation Foundation WPF Application – one of options for Windows projects Vector-based and resolution-independent → sharp graphics As with WinForms, drag and drop controls from the Toolbox onto the window Set property values and register events Some of the names are different (Use Content instead of Text for buttons, labels, checkboxes and radio buttons) C# Programming: From Problem Analysis to Program Design
Windows Presentation Foundation (WPF) RegistrationApp was recreated using WPF C# Programming: From Problem Analysis to Program Design
Windows Presentation Foundation (WPF) Different files created XAML Resembles Hypertext Markup Language (HTML) HTML for Windows application Each control placed on design surface appears as a separate line in the XAML file Beginning and ending tag for each control No .Designer.cs file .xaml.cs is the code behind file for event handlers Review WPF_Example C# Programming: From Problem Analysis to Program Design
TabControl Controls Sometime an application requires too many controls for a single screen TabControl object displays multiple tabs, like dividers in a notebook Each separate tab can be clicked to display other options Add a TabControl object to the page by dragging the control from the Container section of the Toolbox C# Programming: From Problem Analysis to Program Design
TabControl Controls (continued) C# Programming: From Problem Analysis to Program Design
TabControl Controls (continued) C# Programming: From Problem Analysis to Program Design
TabControl Controls (continued) TabPage property enables you to format individual tabs Clicking the ellipsis beside the Collection value displays the TabPage Collection Editor C# Programming: From Problem Analysis to Program Design
TabControl Controls (continued) To indicate tabPage2 should be on top tabControl1.SelectedTab = tabPage2; Can display images on tabs and change the background or foreground colors Tabs can be displayed vertically instead of horizontally using the Alignment property Can register Click events for each of the tabs Review PizzaApp Example C# Programming: From Problem Analysis to Program Design
DinerGUI Application Example C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Table 10-6 Order class data fields C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Figure 10-26 Class diagrams C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Figure 10-27 Pseudocode for the Order class for DinerGUI C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Figure 10-28 Pseudocode for RadioButton, CheckBox, ListBox, and ComboBox object event handlers C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Figure 10-29 Pseudocode for menu object event handlers C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Figure 10-30 Pseudocode for menu object event handlers and ClearDrinks( ) method C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Table 10-7 DinerGUI property values C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Table 10-7 DinerGUI property values (continued) C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Table 10-7 DinerGUI property values (continued) C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Table 10-7 DinerGUI property values (continued) C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Table 10-7 DinerGUI property values (continued) C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) private Order newOrder; private void OrderGUI_Load(object sender, System.EventArgs e) { newOrder = new Order( ); for (int i = 0; i < newOrder.menuEntree.Length; i++) this.lstBxEntree.Items.Add(newOrder.menuEntree[i]); } C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) private void lstBxEntree_SelectedIndexChanged (object sender,System.EventArgs e) { newOrder.Entree = this.lstBxEntree.Text; } private void cmboSpecial_SelectedIndexChanged (object sender, System.EventArgs e) newOrder.SpecialRequest = this.cmboSpecial.Text; Review Diner Example C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Table 10-8 DinerGUI events C# Programming: From Problem Analysis to Program Design
DinerGUI (continued) Table 10-8 DinerGUI events C# Programming: From Problem Analysis to Program Design
Coding Standards Follow a consistent naming standard for controls Before you register events, such as button click events, name the associated control C# Programming: From Problem Analysis to Program Design
Resources Visual Studio - Getting Started Tutorials – http://msdn.microsoft.com/en-us/library/dd492171.aspx Visual C# Windows Forms Tutorials http://visualcsharptutorials.com/windows-forms C# Programmers Reference: Delegates Tutorial – http://msdn.microsoft.com/en-us/library/aa288459(VS.71).aspx C# Programming: From Problem Analysis to Program Design
Resources Delegates and Events in C#/.NET – http://www.akadia.com/services/dotnet_delegates_and_events.html C# Programmers Reference: Delegates Tutorial – http://msdn.microsoft.com/en-us/library/aa288459(VS.71).aspx Microsoft Virtual Academy - C# Fundamentals for Absolute Beginners – http://www.microsoftvirtualacademy.com/training-courses/c-fundamentals-for-absolute-beginners / C# Programming: From Problem Analysis to Program Design
Chapter Summary Delegates Event-handling procedures Registering an event ListBox control for multiple selections ComboBox versus ListBox objects C# Programming: From Problem Analysis to Program Design
Chapter Summary (continued) Adding controls to save space MenuStrip controls TabControl Use of GroupBox controls RadioButton versus CheckBox objects C# Programming: From Problem Analysis to Program Design