INF230 Basics in C# Programming AUBG, COS dept Lecture 41 Event Handling Reference: Doyle, chap 10
Lecture Contents: Delegates and their relationship to events
Chapter 10 Programming Based on Events C# Programming: From Problem Analysis to Program Design 4th Edition
Chapter 10 Programming Based on Events OR Understanding Delegates
Recall data types Value types contain direct values Reference types contain references to (address of) data Examples: SmallObject a = new SmallObject(713); SparePart b = new SparePart(“200D”,45,7.97); int[] c = new int[20];
New: delegates Special Reference types contain references to (address of) a method or methods but not address of data Examples: Reference to method with signature: string return data type and no parameters Reference to method with signature: long return data type, and one int parameter
Delegates Delegates are special types of .NET classes whose instances store references to (addresses of) methods as opposed to storing actual data. By tradition, you pass data into method through the use of parameters. Delegates enable you to pass methods as parameters (as opposed to data) into other methods Delegate signature: Identifies what types of methods the delegate represents For events, it is the address of which method to invoke when an event is fired C# Programming: From Problem Analysis to Program Design
Understanding Delegates Defining Delegates Creating Delegate Instances Using Delegates
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 followed by semicolon 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
Example 1 Special Reference types contain reference to (address of ) a method or methods but not data Example: Delegate as Reference to method with signature: string return data type and no parameters
Defining Delegates Delegate declaration delegate string ReturnsSimpleString( ); Above example represents methods that return a string and require no argument Given the above signature, any method that has zero parameters and returns a string, can be referenced by the ReturnsSimpleString delegate, including three below static string AHeading( ) static string ToString( ) static string EndStatement( ) C# Programming: From Problem Analysis to Program Design
Defining Delegates When you define a delegate type, you identify what types of methods the delegate represents. Think of the delegate as a way of defining or naming a method signature C# Programming: From Problem Analysis to Program Design
Understanding Delegates Defining Delegates Creating Delegate Instances Using Delegates
Creating Delegate Instances 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 one parameter (method name) Name of a method for the constructor to reference When you write a method name without parentheses (as above), you are referencing the address of the method. C# Programming: From Problem Analysis to Program Design
Understanding Delegates Defining Delegates Creating Delegate Instances Using Delegates
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; 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) Figure 9-1 Windows-based form C# Programming: From Problem Analysis to Program Design
Example 1 Type, compile and run the example 1 application
Example 2 Special Reference types contain reference(address) of method or methods but not data Example: Delegate as Reference to method with signature: long return data type, and one int parameter
Example 2 List of methods with required signature static long factr(int n) { if (n == 0) return 1; return n * factr(n - 1); } static long sumr(int n) { if (n == 0) return 0; return n + sumr(n - 1); static long mulr(int n) { if (n == 0 || n == 1) return n; return n * mulr(n - 1);
Example 2 Defining delegates How to declare delegate reference type? Globally located within the namespace delegate long ReturnsLongVal(int par);
Example 2 How to create instance of delegate reference type? Locally located within a method ReturnsLongVal dlgte; dlgte = new ReturnsLongVal(factr); // ReturnsLongVal dlgte = new ReturnsLongVal(factr);
Example 2 How to call a method using delegate? Console.WriteLine(dlgte(5)); Console.WriteLine(dlgte(6));
Example 2 How to call a method using delegate? Console.WriteLine(dlgte(5)); Console.WriteLine(dlgte(6)); dlgte = new ReturnsLongVal(sumr); Console.WriteLine(dlgte(15)); Console.WriteLine(dlgte(16));
Example 2 How to call a method using delegate? Console.WriteLine(dlgte(5)); Console.WriteLine(dlgte(6)); dlgte = new ReturnsLongVal(sumr); Console.WriteLine(dlgte(15)); Console.WriteLine(dlgte(16)); dlgte = new ReturnsLongVal(mulr); Console.WriteLine(dlgte(5+2)); Console.WriteLine(dlgte(6+2));
Example 2 Type, compile and run the example 2 application
Practice Task: Write a program to define delegate ref type and declare instance of delegate as Reference to methods with signature: string return data type and two parameters string data type For indirect access to methods like static string AddStr(string s1, string s2) { return s1 + s2; }
Practice Task: Write a program to define delegate ref type and declare instance of delegate as Reference to methods with signature: integer return data type and two parameters integer data type For indirect access to methods like static int GCDi(int m, int n) static int GCDr(int m, int n)
Practice Task: Write a program to define delegate ref type and declare instance of delegate as Reference to methods with signature: double return data type and two parameters: one double data type and one integer data type For indirect access to methods like static double Powi(double x, int n) static double Powr(double x, int n)
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 VStudio does the work for you . Two things added to the program when Double- clicked on a Button control object during design 1) Button Click event is registered as being of interest 2) An event-handler method heading is generated This two steps process called event wiring process You associate a method in your program to an event . Then, this method is automatically called when the event occurs 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 (Collection …) 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
Fill a List Box at Design Time via its String Collection Editor tasks button click here to invoke string collection editor
Adding a ListBox Control Object Add ListBox control, then click on Items property (Collection) to type entries Figure 10-2 String Collection Editor 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
Multiple selections with ListBox SelectionMode property None One (by default) private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { textBox1.Text = listBox1.Text; } MultiSimple – space bar and clicking the mouse MultiExtended – Ctrl key, Shift key, arrow keys C# Programming: From Problem Analysis to Program Design
Adding items to ListBox at run time private void button1_Click(object sender, EventArgs e) { listBox1.Items.Add(textBox1.Text); } C# Programming: From Problem Analysis to Program Design
Thank You For Your Attention!