INF230 Basics in C# Programming

Slides:



Advertisements
Similar presentations
Chapter 7: Sub and Function Procedures
Advertisements

Microsoft Visual C#.NET: From Problem Analysis to Program Design1 Chapter 9 Programming Based on Events Microsoft Visual C#.NET: From Problem Analysis.
C# Programming: From Problem Analysis to Program Design1 9 Programming Based on Events.
C# Programming: From Problem Analysis to Program Design1 Programming Based on Events C# Programming: From Problem Analysis to Program Design 3 rd Edition.
Programming Based on Events
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
Advanced Object-Oriented Programming Features
Programming Based on Events
C# Programming: From Problem Analysis to Program Design1 Introduction to Windows Programming C# Programming: From Problem Analysis to Program Design 3.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Tutorial 7: Sub and Function Procedures1 Tutorial 7 Sub and Function Procedures.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Six Repeating Program Instructions.
1 Graphical User Interfaces Part 2 Outline ListBoxes and CheckedListBoxes ListBoxes CheckedListBoxes ComboBoxes.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
G RAPHICAL U SER I NTERFACE C ONCEPTS : P ART 1 1 Outline Introduction Windows Forms Event-Handling Model - Basic Event Handling.
COS240 O-O Languages AUBG, COS dept Lecture 33 Title: C# vs. Java (GUI Programming) Reference: COS240 Syllabus.
1 Chapter Eleven Handling Events. 2 Objectives Learn about delegates How to create composed delegates How to handle events How to use the built-in EventHandler.
C# Programming: From Problem Analysis to Program Design1 10 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
Iterations (aka Loops). 2 Loops Loops (iterations) are segments of code that may be executed several times. Fixed-count (definite) loops repeat a fixed.
Unit 6 Repetition Processing Instructor: Brent Presley.
BIL528 – Bilgisayar Programlama II Methods 1. Contents Methods 2.
Lecture Set 7 Procedures and Event Handlers Part B - The Structure of an Application Event Handlers.
1 Introduction to Object Oriented Programming Chapter 10.
Iterations (aka Loops). 2 Loops Loops (iterations) are segments of code (loop body) that may be executed several times. Fixed-count (definite) loops repeat.
COMPUTER PROGRAMMING I Apply Procedures to Develop List Box and Combo Box Objects.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Visual Basic Fundamental Concepts
Programming Right from the Start with Visual Basic .NET 1/e
Chapter 9 Programming Based on Events
Creating Your Own Classes
User-Written Functions
Apply Procedures to Develop Menus, List Box and Combo Box Objects
Computing with C# and the .NET Framework
C# Programming: From Problem Analysis to Program Design
Programming Based on Events
C# Programming: From Problem Analysis to Program Design
IS 350 Application Structure
C# & Windows GUI Applications
Advanced Object-Oriented Programming Features
Delegates and Events 14: Delegates and Events
Chapter 3: Using Methods, Classes, and Objects
Chapter Eleven Handling Events.
Reference: COS240 Syllabus
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Using Procedures and Exception Handling
Apply Procedures to Develop Menus, List Box and Combo Box Objects
Lecturer: Mukhtar Mohamed Ali “Hakaale”
Variables and Arithmetic Operations
Visual Basic..
Programming Based on Events
Microsoft Visual Basic 2005: Reloaded Second Edition
Tutorial 19 - Microwave Oven Application Building Your Own Classes and Objects Outline Test-Driving the Microwave Oven Application Designing.
Delegates & Events 1.
Object Oriented Programming in java
CIS16 Application Development and Programming using Visual Basic.net
CIS 16 Application Development Programming with Visual Basic
Lecture Set 10 Windows Controls and Forms
Web Development Using ASP .NET
Constructors, GUI’s(Using Swing) and ActionListner
How to organize and document your classes
CIS 199 Final Review.
Chapter 13: Handling Events
Creating and Using Classes
Events, Delegates, and Lambdas
Presentation transcript:

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!