Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

Event Driven Programming

1
Outline
Introduction
What's event driven programming?
 Net framework
 Visual Studio 2010
 Defining:
 Controls
 Properties
 Methods
 Namespace

2
What is event driven programming?
• Before Defining event drive programming, we must first know
• what events are?
• Events are the actions that are performed by the user during
the application usage.
• Examples
• Clicking a mouse button
• moving the mouse
• Pressing a Key down/up
• Encountering messages from other programs or thread

3
Event driver programming…?
• Event driver programming (which is also called event-based
programming ) is any programming language, which uses
these events to run a specific portion of the program.
• Other definitions
• It is a programming paradigm in which the flow of the
program is determined by events.
• Event-driven programming is an application architecture
technique in which the application has a main loop which is
clearly divided down to two sections:
• The first is event selection (or event detection), and
• The second is event handling

4
Event driver programming…?
• The event driven programs are very user friendly and
highly interactive systems.
• Event-driven programs can be written in any
language, although the task is easier in languages
that provide high-level abstractions.
• The entire object based languages and visual
languages supports the event driver programming.
• Visual Basic, Visual FoxPro, JavaScript, Visual C++ ,
visual basic.NET, Java, C#, etc are the examples of
these languages.
5
C#
• C# is an object-oriented language and fully supports
the object-oriented programming concepts of
inheritance, polymorphism, encapsulation, and
abstraction.
• C# also supports component-oriented programming,
which enables you to specify units of functionality
(components) that are self-contained and self-
documenting by presenting a model with properties,
methods, events, and metadata about the
component.
6
Types of C# Programs
• Console applications-Console applications run from
the command line which are primarily character- or
text-based.
• Window forms applications-that take advantage of
the graphical user interface (GUI) provided by
Microsoft Windows.
• Web Services-Web Services are routines that can be
called across the Web
• Web form/ASP.NET applications-ASP.NET
applications are executed on a Web server and
generate dynamic Web pages
• etc 7
What is .NET framework
• The MS .NET Framework is a software framework that can be
installed on computers running Ms windows operating
systems.
• The .NET Framework provides an unprecedented platform for
building Windows, web, and mobile applications with one or
more languages.
• To facilitate interoperability between languages, most .NET
Framework types are CLS-compliant and can therefore be
used from any programming language whose compiler
conforms to the common language specification (CLS).
• It also consists of:
– Class library, which includes tested, reusable code for all
major areas of application development.
– The common language runtime (CLR), which provides
memory management and other system services. 8
What is .NET framework

9
Visual Studio
• Visual Studio .NET is Microsoft’s Integrated Development
Environment (IDE) for creating, running and debugging programs
(also called applications) written in a variety of .NET
programming languages.
• This IDE is a powerful and sophisticated tool for creating
business critical and mission-critical applications.
• Prior to beginning Visual Studio installation, you should make
some preliminary checks first.
• You must verify that you meet the system requirements for
installation. (free hard disk space, RAM size and etc)
• In running process actually what is happening?

10
11
Controls and properties
• Those objects (buttons, textboxes, labels, etc) you added to
the form and the form itself, are called control .
• The form itself is a control which contains and used to
assemble other controls.
• Controls can be thought of as things, something solid that
you can pick up and move about.
• Actually, there are also other non-physical controls.
• Controls (things) have properties.
• If your television were a control, it has properties:
– An On/Off button property,
– A colour property,
– Volume property
– Etc
– What other properties would your television have?
12
Properties of Controls…
• The properties of your television will have
values.
– The On/Off button would have just two values -
On or Off.
– The volume property could have a range of values,
from zero to ten, for example.
• If the value of the volume property was set to ten, the
loudest value.

13
Properties of Controls…
• Some of the properties of controls
are : Name, BackColor, Font,
Image, Text, etc.
• Just to the right of these
properties are the values for them
- These values are the default
values, and can be changed.
• The list of properties can be
displayed in a more accessible
form i.e. alphabetically or in
category.
• To display the list properties
alphabetically, click the Alphabetic
icon at the top of the Properties
box, as shown here in the diagram.

14
Method
• A Method is a procedure built into the class.
• They are a series of statements that are
executed when called.
• Methods allow us to handle code in a simple
and organized fashion.
• A block of code with given name.
• A class is a container for these methods.

15
Namespace
• With thousands of classes in the .NET Framework
class library, there needs to be a way to prevent
ambiguity between type names and to provide a
convenient hierarchical grouping mechanism.
• The .NET Framework uses the concept of
namespaces to accomplish this.
• A namespace is simply a collection of types
• The .NET Framework uses the hierarchical nature of
namespaces to provide a progressive framework,
creating a powerful and easy-to-use development
platform. 16
Outline
Programming with event driven
• Variable and constant
• Statement
• Control structure
– Conditional statement
– Loop

17
Variables
• Variables are locations in the computer’s memory
where values can be stored for use by a program.
• All variables must be declared before they can be used
in a program.
• Constants are similar to variables except constants
values does not change unlike variables.
• Visual C# variable declaration has the following format:
type varoable_Name; where
– Variable_Name is the name of a variable
– Type refers the type of the variable whether it is integer,
string, or …
Type Maximum Minimum Size

Data Types sbyte


byte
-128
0
127
255
8
8
• Reference data types are short -32768 32767 16
allocated and released ushort 0 65535 16
dynamically during
int -2147483648 2147483647 32
program execution, their
size might not be known uint 0 4294967295 32
in advance. Example: long
classes (eg: object), ulong
arrays, interfaces. float
• enum, struct types are double
also other data types. decimal
bool true/false
• Reading assignment: char
fill the minimum, string
maximum and size for object
the remaining data types.
DateTime
Variable Declaration and Initialization
• Variable declaration is defining the type and name of a variable.
• Variable initialization is the process of assigning a value to a variable.
• Variables should be declared before a value is assigned to it.
• Examples:
string response; //variable declaration
response = "The answer“; //variable initialization
string response = "The answer“;
bool bLearned = true;
Int x =5;
• Memory locations that hold data that cannot change during execution
are called constants.
• Declaration of constants is the same as declarations of variables except
the keyword const is added at the beginning of the deceleration.
– Example:
• const double discount_Rate = 0.15;
Naming Convention
• Consist of letters, digits, and the underscore character (_)
• Must begin with a letter or underscore
• Reserved words (keywords) are not allowed to be a variable name-
refer page 79 of the book Fundamentals of computer programming with C#
• C# is case sensitive
– NUMBER is not the same as number
Escaping characters
• - \' – single quote Example
char character = '\\';
• - \" – double quotes MessageBox.Show(character);
• - \\ – backslash Output:
• - \n – new line \

• - \t – offset (tab)
• - \uXXXX – char specified by its Unicode number, for example
\u03A7.
21
Example
• int a = 1;
• int b = 2;
• // Which one is greater?
More examples on Page 120 of the book
• bool greaterAB = (a > b); Fundamentals of computer programming
with C#
• if (greaterAB)
• {
• MessageBox.Show("A > B");
• }
• else
• {
• MessageBox.Show("A <= B");
• }
• MessageBox.Show("greaterAB = " + greaterAB); 22
Scope and lifetime of variables
• A variable may exist and be visible for an entire
project, for only one form, for only one
procedure or for a block of code (like inside a
loop only).
• The visibility of a variable is referred to as its
scope
– Local variables
– global variables
• The lifetime of a variable is the period of time
that variable exists.
– The life time of a local variable is normally one
execution of the procedure.
Example1
• namespace VariableScope
• { class Scope
• { public static int m;
• private void btnscope_Click(object sender, EventArgs e)
• { int a = 1;
• if (a == 1)
-m is used in all the methods
• { int b = 0; -a is used only in the main
method
• b = 2; -b is used on in the if block
• m = 7;
• MessageBox.Show(b); }
• MessageBox.Show(a);
• void test()
• { MessageBox.Show(m);
• } }}
24
Example2
• namespace WindowsFormsApplication5
• { public partial class Form1 : Form
• { public Form1()
• { InitializeComponent();
• }
• private void Form1_Load(object sender, EventArgs e)
• { globalVar.global = 100;
• MessageBox.Show((globalVar.global).ToString()); } }
• public static class globalVar
• { static int returnglobal;
• public static int global {
• get { return returnglobal; }
• set { returnglobal = value; }}}}
25
Operators
Allow processing of primitive data types and objects

• Unary-one operand
• Binary-two operand
• Ternary-three operand
26
Arithmetic Operators in The basic logical operators are "AND"
Visual C# (&&), "OR" (||), "exclusive OR" (^) and
logical negation (!).
Addition: +
"AND" (&), bitwise "OR" (|), bitwise
Subtraction: - negation (~), excluding "OR" (^), bit shift
Multiplication: * left (<<) and bit shift right (>>).

Division: / ?: -ternary operand


Modulus: % operand1 ? operand2 : operand3
if operand1 is set to true, the operator
Increment: ++ returns as a result operand2. Otherwise (if
operand1 is set to false), the operator
Decrement: -- returns as a result operand3. Example:
The operator ?? is similar to the int a = 6, b=4; string r;
conditional operator ?:. The difference r=a > b ? "a>b" : "b<=a");
is that it is placed between two MessageBox.Show(r)
operands and returns the left operand
only if its value is not null, otherwise it
returns the right operand. Example:
string name = null;
Console.WriteLine(name ?? "(no
27
name)"); // (no name)
Expression and statement
• Sequences of operators, literals and variables
that are calculated to a value of some type
(number, string, object or other
type)operator+operand
• Statements are made up of one or more
expressions like sentences in English.
• Exercise: Identify the operator, operand,
expression and statement
– Sum=num1+num2
28
Example
Write C# program which takes two numbers as
input and computes their sum and average of
the two numbers.
Example…
• Double click on compute button and write the following code
• private void btnaddaverage_Click(object sender, EventArgs e)
• { int sum, num1;
• int num2,average;
• num1=Convert.ToInt32(txtnum1.Text);
• num2 = Convert.ToInt32(txtnum2.Text);
• sum = num1 + num2;
• average = (num1 + num2) / 2;
• txtsum.Text = Convert.ToString(sum);
• txtaverage.Text = Convert.ToString(average);
• //string result = Convert.ToString(sum);
• //MessageBox.Show(sum.ToString()); }
• Double click on Clear button and write the following code
• private void btnclear_Click(object sender, EventArgs e)
• { txtnum1.Text="";
• txtnum2.Text = "";
txtsum.text=“”;
txtaverage.text=“”;}
• Or: txtnum1.Clear(); etc
Conditional Statements
• Conditional statements evaluates a condition
and produces a true or a false Boolean value
in order to control the flow of code.
• C# has the following conditional statements
– if – single selection statement
– if … else – double selection statement
– if … else if multiple selection statements
– switch – multiple selection statements
if – single selection statement
• The simplest control statement—and one that
is common to almost every programming
language—is the If statement.
• This statement has several different formats
but basically it looks like this:
– Basic Syntax: if (condition) { statements; }
• The (condition) is the key part of this statement
(made of boolean expression)
– It determines whether or not the inner block of
code is executed.
if … else – double selection statement
• The if…else selection structure allows the programmer to
specify that a different action (or sequence of actions) be
performed when the condition is false.
• Syntax:
if (condition)
statements;
else
else statement;

• E.g.
int mark;
if (mark>60);
{MessageBox.Show(“Pass”);}
else
{MessageBox.Show(“Fail”);}
if … else if multiple selection statement
• Generally, If…Then…Else Conditional
Statement has the following structure
if (condition) {
statements;
}
else If <condition>; {
elseif_statements ;
}
else{
else_statements;
}
Example1
The following application takes two numbers and returns larger number
• private void btnlarger_Click(object sender, EventArgs e)
• {
• int num1, num2;
• num1 = Convert.ToInt32(txtnum1.Text);
• num2 = Convert.ToInt32(txtnum2.Text);
• if (num1 > num2)
• {
• MessageBox.Show(num1 + " is greater than " + num2);
• }
• else if (num1 < num2)
• {
• MessageBox.Show(num2 + " is greater than " + num1);
• }
• else
• {
• MessageBox.Show(num1 + " is equal to " + num2);
• }
• }
Or using nested if
• int first = 5;
• int second = 3;
• if (first == second)
• { Console.WriteLine("These two numbers are equal."); }
• else
• { if (first > second)
• { Console.WriteLine("The first number is greater."); }
• else
• {Console.WriteLine("The second number is greater.");
• }
• }
36
Example 2
• To display the tariff for taxi transport
• string userValue = “”
• string message = "";
• if (userValue == "14")
• message = “It is Birr 1 and 50 Cents";
• else if (userValue == “Peda")
• message = “It is Birr 1";
• else if (userValue == “Hospital")
• message = “It is Birr 2";
• else
• message = “Invalid path, please feed the correct path!";
• MessageBox.Show(message);

37
switch – multiple selection statement
• The switch statement Replaces multiple if ..
else statements
• Syntax:
switch ( expression ){
case value1: statement; break;
case value2: statement; break;
// etc.
default: statement;
}
Example1
int age= Convert.ToInt32(txtage.Text);
switch ( age ) {
case 13 : textBox1.Text = "you are a teenager"; break ;
case 18 : textBox1.Text = "you can vote"; break ;
case 21 : textBox1.Text = "congratulations"; break ;
default : textBox1.Text = "You are not 13, 18 or 21.";break ;}
• Note the break statement – it must be there
• you can only continue to the next statement if it is empty (the statement is
executed for case 1 and 2).
For a range of value
case 1 : int range = (num-1) / 500;
case 2 : switch (range) {
textBox1.Text = "executed for case 1 or 2"; case 0: break; // 1-500
case 1: break; // 501-1000
break ;
Example2
• string userValue = “”
• string message = "";
Switch(uservalue){
• case "14“:
• message = “It is Birr 1 and 50 Cents";
break;
• case “Peda“:
• message = “It is Birr 1";
break;
• case “Hospital“:
• message = “It is Birr 2";
break;
• default:
• message = “Invalid path, please feed the correct path!";
break; } MessageBox.Show(message); 40
Exercise 1
• Write C# application that takes result of a student
out of 100 and assigns letter grade to the input value
based on the following scale.
• 100>X>90----------------->A
• 90>X>70------------------->B
• 70>X>50------------------->C
• 50>X>40------------------->D
• 40>X>0--------------------->F
• >100 and <0-------------->Invalid Input
Exercise2
• Develop C#
application that
solves quadratic
equation. The
user interface of
the application
should look like
the one on the
right
C# Loops
• Loops
– A loop is a basic programming construct that
allows repeated execution of a fragment of source
code.
• for loop
• foreach loop
• while loop
• do while loop
• break and continue statements
43
For loop
• Used when you know the details of the loop
– the start, increment and end values
for (variable = start_expr; end_expr;incr_expr) {
statement(s);
}
Example :
for (int counter = 0; counter <= 9; counter++){
lstData.Items.Add(“Number =" +counter);
} // end of for loop

44
foreach Loop
• A variation of the For loop, the foreach loop
scans through a set of related item from the
first item until the last.
• E.g : Arrays and collection
• Syntax:
foreach(var type Var In Array or Collection ){
statements to be repeated ;
}

45
Example 1:
• private void btnforechloop_Click(object sender, EventArgs e)
• {
• int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7,8,9 };
• foreach (int i in numbers)
• {
• lstData.Items.Add("Number:" + i);
• }}
Example 2:
• string[] towns = { “Addis Ababa", “Jimma", “Bahir Dar",
“Lalibela" };
• foreach (string town in towns)
• {
• lstData.Items.Add(" " + town);
• } 46
The while loop
• Used to change counter by different amount or test within
the loop
Syntax:
while (condition) {
statement(s);
}
• Condition is evaluated at the beginning of the loop.
• The statement(s) are executed while condition is true.
Example:

private void btnWhile_Click(object sender, EventArgs e)


{
int counter = 0;
while (counter <= 9)
{
lstData.Items.Add("Number : " + counter);
counter++;
}
}

47
The do-while loop
• Similar to while loop
• Condition is evaluated at the end of the loop.
• Syntax:
do{
statement(s);
}
while (condition); // Note semicolon
• The statement(s) are executed at least once.
Example:
• private void btndowhile_Click(object sender, EventArgs e)
• { int counter = 0;
• do
• { lstData.Items.Add("Number : " + counter);
• counter++;
• } while (counter <= 9); 48
break statement
• break statement exits the loop that contains the statement.
Example: calculate factorial
• int n = int.Parse(txtnum.Text);
• decimal factorial = 1;
• while (true)
• {
• if (n <= 1)
• {
• break;
• }
• factorial *= n;
• n--;
• }
• MessageBox.Show("n! = " + factorial);
49
Continue statement
• Allow us to go to the next iteration with out executing codes
after continue statement but inside a loop. Example: That
sums number except those divisible by 7.
• int n = int.Parse(txtnum.Text);
• int sum = 0;
• for (int i = 1; i <= n; i += 2)
• {
• if (i % 7 == 0)
• {
• continue;
• }
• sum += i;
• }
• MessageBox.show("sum = " + sum); 50
Nested Loop-loop inside loop
• Example: List prime numbers b/n two numbers
• private void btnprime_Click(object sender, EventArgs e)
• { int n = int.Parse(txtnum1.Text);
• int m = int.Parse(txtnum2.Text);
• for (int num = n; num <= m; num++)
• {bool prime = true;
• int divider = 2;
• int maxDivider = (int)Math.Sqrt(num);
• while (divider <= maxDivider)
• { if (num % divider == 0) Exercise: Using nested loop:
• { prime = false; break; 1.Print matrix
• } divider++; } 2. Print the following:
1
• if (prime) { lstPrime.Items.Add(num);}} } 1 2
51
123
Exercise
• Sum numbers ranging from 1 to N.
• Check whether a given number is a prime.
• Use BigInteger data type to calculate factorial
of large numbers (To insert reference: right
click on referenceadd reference.Net
tabselect System.Numericsok
• Find the product b/n two numbers N and M
• Find N the power of M using loop
52

You might also like