Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# Programming: From Problem Analysis to Program Design

Similar presentations


Presentation on theme: "C# Programming: From Problem Analysis to Program Design"— Presentation transcript:

1 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

2 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 Using Delegates (continued)
Review DelegateExample C# Programming: From Problem Analysis to Program Design

12 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

13 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

14 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

15 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

16 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

17 ListBox Control Properties
Table ListBox properties C# Programming: From Problem Analysis to Program Design

18 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

19 ListBox Control Methods
Events are methods….Default event for ListBox Table ListBox methods C# Programming: From Problem Analysis to Program Design

20 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

21 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

22 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

23 ListBox Control Objects (continued)
C# Programming: From Problem Analysis to Program Design

24 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

25 ListBox Control Objects (continued)
C# Programming: From Problem Analysis to Program Design

26 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

27 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

28 ListBoxExample C# Programming: From Problem Analysis to Program Design

29 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

30 ListBoxExample (continued)
Table ListBoxExample property values C# Programming: From Problem Analysis to Program Design

31 ListBoxExample (continued)
Table ListBoxExample property values (continued) C# Programming: From Problem Analysis to Program Design

32 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

33 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

34 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

35 Adding ComboBox Controls
Extra TextBox object with ComboBox – User selects from list or types new value C# Programming: From Problem Analysis to Program Design

36 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

37 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

38 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

39 Programming Event Handlers (continued)
C# Programming: From Problem Analysis to Program Design

40 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

41 Adding Menus Drag MenuStrip control to form, then click here to display Menu structure C# Programming: From Problem Analysis to Program Design

42 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

43 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

44 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

45 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

46 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

47 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

48 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

49 Adding Predefined Standard Windows Dialog Boxes
C# Programming: From Problem Analysis to Program Design

50 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

51 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

52 Adding Predefined Standard Windows Dialog Boxes – Color
C# Programming: From Problem Analysis to Program Design

53 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

54 GardeningForm Properties
Each entry has an associated statement in the .Designer.cs file Table GardeningForm property values C# Programming: From Problem Analysis to Program Design

55 GardeningForm Properties (continued)
Table GardeningForm property values (continued) C# Programming: From Problem Analysis to Program Design

56 GardeningForm Properties (continued)
Table GardeningForm property values (continued) C# Programming: From Problem Analysis to Program Design

57 GardeningForm Properties (continued)
Table GardeningForm property values (continued) C# Programming: From Problem Analysis to Program Design

58 GardeningForm Events Table 10-5 GardeningForm events
C# Programming: From Problem Analysis to Program Design

59 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

60 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

61 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

62 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

63 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

64 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

65 Adding RadioButton Objects
Box drawn around RadioButton objects is from GroupBox C# Programming: From Problem Analysis to Program Design

66 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

67 Wiring One Event Handler to Multiple Objects (continued)
Each CheckBox and RadioButton wired to same method C# Programming: From Problem Analysis to Program Design

68 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

69 ComputeCost_CheckChanged( ) and Click( ) Events Raised
C# Programming: From Problem Analysis to Program Design

70 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

71 Windows Presentation Foundation (WPF)
RegistrationApp was recreated using WPF C# Programming: From Problem Analysis to Program Design

72 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

73 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

74 TabControl Controls (continued)
C# Programming: From Problem Analysis to Program Design

75 TabControl Controls (continued)
C# Programming: From Problem Analysis to Program Design

76 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

77 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

78 DinerGUI Application Example
C# Programming: From Problem Analysis to Program Design

79 DinerGUI (continued) Table 10-6 Order class data fields
C# Programming: From Problem Analysis to Program Design

80 DinerGUI (continued) C# Programming: From Problem Analysis to Program Design

81 DinerGUI (continued) Figure 10-26 Class diagrams
C# Programming: From Problem Analysis to Program Design

82 DinerGUI (continued) Figure Pseudocode for the Order class for DinerGUI C# Programming: From Problem Analysis to Program Design

83 DinerGUI (continued) Figure 10-28 Pseudocode for RadioButton,
CheckBox, ListBox, and ComboBox object event handlers C# Programming: From Problem Analysis to Program Design

84 DinerGUI (continued) Figure Pseudocode for menu object event handlers C# Programming: From Problem Analysis to Program Design

85 DinerGUI (continued) Figure Pseudocode for menu object event handlers and ClearDrinks( ) method C# Programming: From Problem Analysis to Program Design

86 DinerGUI (continued) Table 10-7 DinerGUI property values
C# Programming: From Problem Analysis to Program Design

87 DinerGUI (continued) Table 10-7 DinerGUI property values (continued)
C# Programming: From Problem Analysis to Program Design

88 DinerGUI (continued) Table 10-7 DinerGUI property values (continued)
C# Programming: From Problem Analysis to Program Design

89 DinerGUI (continued) Table 10-7 DinerGUI property values (continued)
C# Programming: From Problem Analysis to Program Design

90 DinerGUI (continued) Table 10-7 DinerGUI property values (continued)
C# Programming: From Problem Analysis to Program Design

91 DinerGUI (continued) C# Programming: From Problem Analysis to Program Design

92 DinerGUI (continued) C# Programming: From Problem Analysis to Program Design

93 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

94 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

95 DinerGUI (continued) C# Programming: From Problem Analysis to Program Design

96 DinerGUI (continued) C# Programming: From Problem Analysis to Program Design

97 DinerGUI (continued) C# Programming: From Problem Analysis to Program Design

98 DinerGUI (continued) Table 10-8 DinerGUI events
C# Programming: From Problem Analysis to Program Design

99 DinerGUI (continued) Table 10-8 DinerGUI events
C# Programming: From Problem Analysis to Program Design

100 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

101 Resources Visual Studio - Getting Started Tutorials –
Visual C# Windows Forms Tutorials C# Programmers Reference: Delegates Tutorial – C# Programming: From Problem Analysis to Program Design

102 Resources Delegates and Events in C#/.NET –
C# Programmers Reference: Delegates Tutorial – Microsoft Virtual Academy - C# Fundamentals for Absolute Beginners – / C# Programming: From Problem Analysis to Program Design

103 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

104 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


Download ppt "C# Programming: From Problem Analysis to Program Design"

Similar presentations


Ads by Google