SlideShare une entreprise Scribd logo
1  sur  128
Télécharger pour lire hors ligne
Nawroz University
Object Oriented
Programming
C-Sharp Programming
C# provides full support for object-oriented
programming including encapsulation,
inheritance, and polymorphism.
[2017/
2018]
Rekany
Renas Rajab Rekany
2017/2018
Renas Rajab Rekany OOP 2018
1
Object Oriented Programming
History of programming languages
1- Microsoft .Net Framework
.NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs
primarily on Microsoft Windows. It includes a large class library known as Framework Class Library (FCL)
and provides language interoperability(each language can use code written in other languages) across
several programming languages. Programs written for .NET Framework execute in a software environment
(as contrasted to hardware environment), known as Common Language Runtime (CLR), an application
virtual machine that provides services such as security, memory management, and exception handling. FCL
and CLR together constitute .NET Framework.
FCL provides user interface, data access, database connectivity, cryptography, web
application development, numeric algorithms, and network communications. Programmers produce
software by combining their own source code with .NET Framework and other libraries. .NET
Framework is intended to be used by most new applications created for the Windows platform.
Microsoft also produces an integrated development environment largely for .NET software
called Visual Studio.
2-Different DOTNET Types of Applications
There are three main types of application that can be written in C#:
1. Winforms: Windows applications have the familiar graphical user interface of Windows
with controls such as buttons and list boxes for input.
2. Console: Console applications use standard command-line input and output for input and
output instead of a form.
3. Web Sites.
Renas Rajab Rekany OOP 2018
2
4- Create First Winforms application
Step 1: Start Visual Studio
Open the Microsoft Visual Studio 2008/2015.
Step 2: Create a new project
Go to File -> New Project, And then New Project Dialog Appears.
In the New Project Window, Select Visual C# as Project type and Windows Forms
Applications as the template. Give Name and Location to your project and finally
click OK button to create our first C# project.
Renas Rajab Rekany OOP 2018
3
Renas Rajab Rekany OOP 2018
4
Step 3: Design the user interface.
When the project is created, you will see the designer view of your interface as
follows.
Form Designer View
In this designer view of the form (Form1.cs [Design]), you can design the user
interface of the single form. To do that, we use the 'Toolbox' which contains the
items that you can add to your form. Toolbox is placed on the left side of your visual
studio. If it is not visible go to View -> Toolbox to show the Toolbox.
Toolbox
Renas Rajab Rekany OOP 2018
5
It contains Labels, Buttons, Check Boxes, Combo Boxes and etc. This can be used to
design your interface. To add elements from the Toolbox to your form double click
the item or drag the item to your form.
Now add a Button Control to your form by simple dragging a Button control into the
form designer view. Finally it looks like below.
Now our form contains two elements. Those are form and the button control. These
elements have properties such as name, text, background color, fore color, etc.... To
see properties for a control, select the control and all the properties are displayed in
the Properties Window which appears on the right side of your visual studio. If it is
not visible, Go to View -> Properties Window.
Select the button and view properties as follows.
Now set the text to 'Show' for the button.
Renas Rajab Rekany OOP 2018
6
Step 4: Writing the code
Double click on buttun1 to write the code
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello World!");
}
Step 5: Compile the code
To compile the code Go to Build -> Build HelloWorld
Step 6: Running the application
To run/execute the program press F5.
Renas Rajab Rekany OOP 2018
7
Running Application.
6- Create First Web application
Building Your First Web Application Project
Creating a New Project
Select File->New Project within the Visual Studio 2005 IDE. This will bring up the New Project
dialog. Click on the “Visual C#” node in the tree-view on the left hand side of the dialog box and
choose the "ASP.NET Web Application" icon:
Renas Rajab Rekany OOP 2018
8
Visual Studio will then create and open a new web project within the solution explorer. By default
it will have a single page (Default.aspx), an AssemblyInfo.cs file, as well as a web.config file. All
project file-meta-data is stored within a MSBuild based project file.
Renas Rajab Rekany OOP 2018
9
Opening and Editing the Page
Double click on the Default.aspx page in the solution explorer to open and edit the page. You can
do this using either the HTML source editor or the design-view. Add a "Hello world" header to the
page, along with a calendar server control and a label control (we'll use these in a later tutorial):
Build and Run the Project
Hit F5 to build and run the project in debug mode. By default, ASP.NET Web Application projects
are configured to use the built-in VS web-server when run. The default project templates will run
on a random port as a root site (for example: http://localhost:12345/):
Renas Rajab Rekany OOP 2018
10
You can end the debug session by closing the browser window, or by choosing the Debug->Stop
Debugging (Shift-F5) menu item.
Customizing Project Properties
ASP.NET Web Application Projects share the same configuration settings and behaviors as
standard VS 2005 class library projects. You access these configuration settings by right-clicking
on the project node within the Solution Explorer in VS 2005 and selecting the "Properties" context-
menu item. This will then bring up the project properties configuration editor. You can use this to
change the name of the generated assembly, the build compilation settings of the project, its
references, its resource string values, code-signing settings, etc:
Renas Rajab Rekany OOP 2018
11
ASP.NET Web Application Projects also add a new tab called "Web" to the project properties list.
Developers use this tab to configure how a web project is run and debugged. By default, ASP.NET
Web Application Projects are configured to launch and run using the built-in VS Web Server (aka
Cassini) on a random HTTP port on the machine.
This port number can be changed if this port is already in use, or if you want to specifically test and
run using a different number:
Renas Rajab Rekany OOP 2018
12
Alternatively, Visual Studio can connect and debug IIS when running the web application. To use
IIS instead, select the "Use IIS Web Server" option and enter the url of the application to launch,
connect-to, and use when F5 or Control-F5 is selected:
Renas Rajab Rekany OOP 2018
13
Then configure the url to this application in the above property page for the web project. When you
hit F5 in the project, Visual Studio will then launch a browser to that web application and
automatically attach a debugger to the web-server process to enable you to debug it.
Note that ASP.NET Web Application Projects can also create the IIS vroot and configure the
application for you. To do this click the "Create Virtual Directory" button.
Renas Rajab Rekany OOP 2018
14
Introduction to C#
Comments
1- Single Line ( // )
Ex: int x,y,s;
S=x+y; // the sum of x,y
2- Multiple Line (/* */)
Ex: int x,y,s;
S=x+y; /* the sum
of x,y */
Arithmetic Operations
Operations Arithmetic in c#
Addition +
Subtraction -
Multiplication *
Division /
Modulus %
Precedence of Arithmetic Operations
( )
*,/,%
+,-
<,<=,>,>=
==,!=
=
Ex z = p * r ٪ q + w / x – y
(6) (1) (2) (4) (3) (5)
Ex y = a * x * x + b * x + c
(6) (1) (2) (4) (3) (5)
Renas Rajab Rekany OOP 2018
15
Equality and Relational Operator
Standard Operator C# Operator Ex in C#
= == If (x==y)
≠ != If (x!=y)
> > If (x>y)
≥ >= If (x>=y)
< < If (x<y)
≤ <= If (x<=y)
Assignment operations
int c;
c=c+3; c+=3;
c ‫ــ‬ =3;
c*=3;
c/=3;
(var) = (var) (operator) (expiration)
If true
(var) (operator) = (expiration)
Increment and Decrement Operator
Operator Call Ex
++ Pre Increment ++ a
++ Post Increment a++
-- Pre Decrement --b
-- Post Decrement b--
Ex : int c=5;
MessageBox.Show(c); //5
MessageBox.Show(c++); // 5
MessageBox.Show(++c); // 6
C=5;
MessageBox.Show(c); // 5
MessageBox.Show(++c); // 6
MessageBox.Show(c); // 6
Renas Rajab Rekany OOP 2018
16
Loop Statement in C#
For While Do-While
For (int ; condition ;
increment)
Ex :
For (int i=0;i<=5;i++)
Textbox1.text=textbox1.text+i;
0
1
2
3
4
5
While (condition)
State;
Ex :
int i=0;
While (i<=5)
{
Textbox1.text=textbox1.text+ i;
i i =i+1;
}
0
1
2
3
4
5
Do
{ State}
While (condition);
Ex :
int i=0;
do
{
Textbox1.text=textbox1.text+ i;
i++;
} While (i<=5);
0
1
2
3
4
5
Declarations and types
1- Goals:
1-Learn C# program structure
2-Learn what comments are.
3-Know different types of C# data types
4- Learn what Variables are.
2- General Structure of a C# Program
Well, you have understand where to and how to execute your program. Each
program requires three important steps to do the work. Input, Process and Output. It
is the basic concept of almost all the programming language. It is also known as
Renas Rajab Rekany OOP 2018
17
I-P-O cycle. The program requires some input from the user. Next, the program
processes the input with programming language and finally shows the output.
The basic structure of c# program:
Using System;
namespace newproject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
3- Create and run a GUI (Graphic user Interface) project
Step 1: Start Visual Studio
Open the Microsoft Visual Studio 2008.
Step 2: Create a new project
Go to File -> New Project, And then New Project Dialog Appears. In the New
Project Window, Select Visual C# as Project type and windows form Application as
the template.
Step 3: Writing the code
Under the standard structure of c# program Add the following code which you will
enter your name and your name will be displayed with some text message in the
form.
Renas Rajab Rekany OOP 2018
18
using System;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "Hello Students";
}
}
}
Step 4: Run your application
Press F5
Step 5: Output:
4- Example1 Explanation:
using System;
It is used for including C# class library. C# has huge collection of classes and objects. If
you want to use those classes then you will have to include their library name in your
program.
string name; //Variable for storing string value
int name; // Variable for storing integer value
Renas Rajab Rekany OOP 2018
19
.
Input: For storing values into the specific variables. Eg.
int a;
a=5;
string s;
s="Hello";
Output: For getting result from the specific operations. Eg.
int a;
a=5;
textbox1.text=Convert.Tostring(a);
5- Comments
The first line contains a comment. The characters // convert the rest of the line to a
comment.
// A Hello World! program in C#.
You can also comment out a block of text by enclosing it between the /* and */ characters.
This is shown in the following example.
/* A "Hello World!" program in C#.
This program displays the string "Hello World!" on the screen. */
6- C# Data Types
A complete detail of C# data types are mentioned below:
Data Types Size Values
sbyte 8 bit -128 to 127
byte 8 bit 0 to 255
Renas Rajab Rekany OOP 2018
20
short 16 bit -32,768 to 32,767
ushort 16 bit 0 to 65,535
int 32 bit -2,147,483,648 to 2,147,483,647
uint 32 bit 0 to 4,294,967,295
long 64 bit -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong 64 bit 0 to 18,446,744,073,709,551,615
char 16 bit 0 to 65535
float 32 bit -1.5 x 1045 to 3.4 x 1038
double 64 bit -5 x 10324 to 1.7 x 10308
decimal 128 bit -1028 to 7.9 x 1028
bool --- True or false
6- Example1: Write a program in c# to find the result of adding two values.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Renas Rajab Rekany OOP 2018
21
int a, b,c;
a =Convert.ToInt32( textBox1.Text);
b =Convert.ToInt32( textBox2.Text);
c = a + b;
textBox3.Text = Convert.ToString(c);
}
}
}
OUTPIT:
7- Example2: Write a program in c# to find the result of multiplying two values.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int a, b,c;
a =Convert.ToInt32( textBox1.Text);
Renas Rajab Rekany OOP 2018
22
b =Convert.ToInt32( textBox2.Text);
c = a * b;
textBox3.Text = Convert.ToString(c);
} }}
OUTPUT:
8- Conversion
C# accepts string value by default. If you are using other value then you will have to
convert of specific data types.
num1 = int32.Parse(Console.ReadLine());
You can use the following method to convert one data type to another data type.
Integer = int32.parse() or Convert.ToInt32()
int=Convert.ToInt32(string);
String=Convert.ToString(integer);
Double=Convert.ToDouble();
Decimal=Convert.ToDecimal();
Byte=Convert.ToByte();
Renas Rajab Rekany OOP 2018
23
For Example:
private void button1_Click(object sender, EventArgs e)
{
int a, b,c;
a =Convert.ToInt32( textBox1.Text);
b =Convert.ToInt32( textBox2.Text);
c = a * b;
textBox3.Text = Convert.ToString(c);
}
Beginning C# programming fundamentals
1- Name Spaces:
The namespace keyword is used to declare a scope that contains a set of related
objects. You can use a namespace to organize code elements and to create globally
unique types.
2- Conversion:
You can convert a string to a number by using methods in the Convert class. Such a
conversion can be useful when obtaining numerical input from a command line
argument, for example. The following table lists some of the methods that you can
use.
Renas Rajab Rekany OOP 2018
24
2.1 Convert Class
Numeric Type Method
decimal ToDecimal(String)
float ToSingle(String)
double ToDouble(String)
short ToInt16(String)
int ToInt32(String)
long ToInt64(String)
Structure Conversion Method
Decimal static decimal Parse(string str)
Double static double Parse(string str)
Single static float Parse(string str)
Int64 static long Parse(string str)
Int32 static int Parse(string str)
Int16 static short Parse(string str)
UInt64 static ulong Parse(string str)
UInt32 static uint Parse(string str)
UInt16 static ushort Parse(string str)
Byte static byte Parse(string str)
bool static bool Parse(string str)
SByte static sbyte Parse(string str)
Renas Rajab Rekany OOP 2018
25
Example1:
3- Relational Operator:
In most cases, the Boolean expression, used by the if statement, uses relation
operators
string name;
int mark;
name ="Redwan"
mark = Int32.Parse(85);
textbox1.text=name;
textbox2.text=Convert.ToString(mark);
Renas Rajab Rekany OOP 2018
26
4- Boolean Expressions:
A Boolean expression is any variable or calculation that results in a true or false
condition.
5- Condition control structure
Thus far, within a given function, instructions have been executed sequentially, in the
same order as written. Of course that is often appropriate! On the other hands if you
are planning out instructions, you can get to a place where you say, “Hm, that
depends....”, and a choice must be made. The simplest choices are two-way: do one
thing is a condition is true, and another (possibly nothing) if the condition is not true.
5.1The if Statement
The if statement decides whether a section of code executes or not. The if statement
uses a Boolean to decide whether the next statement or block of statements executes.
The general C# if syntax is:
Renas Rajab Rekany OOP 2018
27
if (expression )
{Statement(s) for if-true}
Example2
:
5.2 if-else Statements
The general C# if-else syntax is
if (expression )
{Statement(s) for if-true}
else
{statement(s) for if-false}
Example3:
5.3 if-else-if Statements
if (expression_1)
{
statement;
statement;
etc.
}
Otherwise, if expression_2 is true these statements
are executed, and the rest of the structure is
ignored.
Insert as many else if clauses as necessary.
If expression_1 is true these statements are
executed, and the rest of the structure is ignored.
int x=2,y=4;
if(x>y)
MessageBox.Show("True");
Renas Rajab Rekany OOP 2018
28
else if (expression_2)
{
statement;
statement;
etc.
}
else
{
statement;
statement;
etc
Example4:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
These statements are executed if none of the
expressions above are true.
int x=2,y=4;
if(x>y)
MessageBox.Show("True");
else
MessageBox.Show("False");
Renas Rajab Rekany OOP 2018
29
int a, b, c;
a = Convert.ToInt32(textBox2.Text);
b = Convert.ToInt32(textBox3.Text);
if (Convert.ToInt32(textBox1.Text) == 1)
{
c = a + b;
textBox4.Text = Convert.ToString(c);
}
else if (Convert.ToInt32(textBox1.Text)==2)
{
c=a-b;
textBox4.Text=Convert.ToString(c);
}
else if (Convert.ToInt32(textBox1.Text) == 3)
{
c = a * b;
textBox4.Text = Convert.ToString(c);
}
else if (Convert.ToInt32(textBox1.Text) == 4)
{
c = a / b;
textBox4.Text = Convert.ToString(c);
}
}
}
}
Example5 (Switch- Condition):
switch (value)
{
case value 1:
statements
break;
case value 2:
Renas Rajab Rekany OOP 2018
30
statements
break;
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int a, b, c;
a = Convert.ToInt32(textBox2.Text);
b = Convert.ToInt32(textBox3.Text);
switch (Convert.ToInt32(textBox1.Text))
{
case 1:
c = a + b;
textBox4.Text = Convert.ToString(c);
break;
case 2:
c = a - b;
textBox4.Text = Convert.ToString(c);
break;
case 3:
c = a * b;
Renas Rajab Rekany OOP 2018
31
textBox4.Text = Convert.ToString(c);
break;
case 4:
c = a / b;
textBox4.Text = Convert.ToString(c);
break;
} } } }
OUTPUT:
String Functions Definitions
Clone() Make clone of string.
CompareTo()
Compare two strings and returns integer value as output. It
returns 0 for true and 1 for false.
Contains()
The C# Contains method checks whether specified
character or string is exists or not in the string value.
EndsWith()
This EndsWith Method checks whether specified character
is the last character of string or not.
Equals()
The Equals Method in C# compares two string and returns
Boolean value as output.
GetHashCode() This method returns HashValue of specified string.
GetType() It returns the System.Type of current instance.
GetTypeCode() It returns the Stystem.TypeCode for class System.String.
IndexOf() Returns the index position of first occurrence of specified
Renas Rajab Rekany OOP 2018
32
character.
ToLower()
Converts String into lower case based on rules of the
current culture.
ToUpper()
Converts String into Upper case based on rules of the
current culture.
Insert()
Insert the string or character in the string at the specified
position.
IsNormalized()
This method checks whether this string is in Unicode
normalization form C.
LastIndexOf()
Returns the index position of last occurrence of specified
character.
Length It is a string property that returns length of string.
Remove()
This method deletes all the characters from beginning to
specified index position.
Replace() This method replaces the character.
Split() This method splits the string based on specified value.
StartsWith()
It checks whether the first character of string is same as
specified character.
Substring() This method returns substring.
ToCharArray() Converts string into char array.
Trim()
It removes extra whitespaces from beginning and ending of
string.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
Renas Rajab Rekany OOP 2018
33
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string s,fn, ln;
fn = textBox1.Text;
ln = textBox2.Text;
s = comboBox1.Text;
switch (s)
{
case "Clone":
textBox3.Text=Convert.ToString( fn.Clone());
textBox4.Text=Convert.ToString(ln.Clone());
break;
case "CompareTo":
int b = fn.CompareTo(ln);
if (b == 0)
MessageBox.Show("False");
else if (b == 1)
MessageBox.Show("True");
break;
case "Contains":
MessageBox.Show(Convert.ToString( fn.Contains("W")));
break;
Renas Rajab Rekany OOP 2018
34
case "EndsWith":
MessageBox.Show(Convert.ToString( fn.EndsWith("d")));
break;
case "Equals":
MessageBox.Show(Convert.ToString( fn.Equals(ln)));
break;
case "GetHashCode":
textBox3.Text =Convert.ToString( fn.GetHashCode());
textBox4.Text =Convert.ToString( ln.GetHashCode());
break;
case "GetType":
textBox3.Text = Convert.ToString(fn.GetType ());
textBox4.Text = Convert.ToString(ln.GetType ());
break;
case "GetTypeCode":
textBox3.Text = Convert.ToString(fn.GetTypeCode ());
textBox4.Text = Convert.ToString(ln.GetTypeCode ());
break;
case "IndexOf":
textBox3.Text = Convert.ToString(fn.IndexOf("e"));
textBox4.Text = Convert.ToString(ln.IndexOf("o"));
break;
case "ToLower":
textBox3.Text = Convert.ToString(fn.ToLower());
textBox4.Text = Convert.ToString(ln.ToLower());
break;
case "ToUpper":
textBox3.Text = Convert.ToString(fn.ToUpper());
textBox4.Text = Convert.ToString(ln.ToUpper());
break;
case "Insert":
textBox3.Text = Convert.ToString(fn.Insert(0, "Hi "));
textBox4.Text = Convert.ToString(ln.Insert(0, " Hi "));
Renas Rajab Rekany OOP 2018
35
break;
case "IsNormalized":
MessageBox.Show(Convert.ToString(fn.IsNormalized()));
break;
case "LastIndexOf":
textBox3.Text = Convert.ToString(fn.LastIndexOf("o"));
textBox4.Text = Convert.ToString(ln.LastIndexOf("s"));
break;
case "Length":
textBox3.Text = Convert.ToString(fn.Length);
textBox4.Text = Convert.ToString(ln.Length);
break;
case "Remove":
textBox3.Text = Convert.ToString(fn.Remove(5));
textBox4.Text = Convert.ToString(ln.Remove(0,4));
break;
case "Replace":
textBox3.Text = Convert.ToString(fn.Replace("o", "*"));
textBox4.Text = Convert.ToString(ln.Replace("w", "*"));
break;
case "Split":
string[] split1 = fn.Split(new char[] { 'o' });
textBox3.Text = split1[0];
string[] split2 = ln.Split(new char[] { 'd' });
textBox4.Text = split2[1];
break;
case "StartsWith":
textBox3.Text=Convert.ToString(fn.StartsWith("O"));
textBox4.Text = Convert.ToString(ln.StartsWith("W"));
break;
case "SubString":
textBox3.Text = Convert.ToString(fn.Substring(2, 5));
textBox4.Text = Convert.ToString(ln.Substring(4, 5));
Renas Rajab Rekany OOP 2018
36
break;
case "ToCharArray":
char[] s1 = fn.ToCharArray();
char [] s2= ln.ToCharArray();
for (int i = 0; i < fn.Length; i++)
{
textBox3.Text = textBox3.Text + s1[i];
}
for (int i = 0; i < ln.Length ; i++)
{
textBox4.Text = textBox4.Text + s2[i];
}
break;
case "Trim":
textBox3.Text = Convert.ToString(fn.Trim());
textBox4.Text = Convert.ToString(ln.Trim(new char[] {'s'}));
break;
}
}
}
}
Renas Rajab Rekany OOP 2018
37
Loop control structure
1- Goals:
In this chapter you will learn:
• What is Loop Constructs in C#?
• How many types of looping statements in C sharp?
• How to use loop constructs in Programming?
H.M) Write a program in C# to enter 10 degrees, then find the Grade for each of
them.
2- Loop constructs
The loop constructs is used to execute a block of code until the condition becomes
expired. Loop constructs in C#, saves the programmer from writing code multiple
times that has repetitive in nature.
2.1 For Loop:
Renas Rajab Rekany OOP 2018
38
Example 1:
OUTPUT
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string a;
a = "aa";
for (int i = 0; i < 5; i++)
{
textBox1.Text = textBox1.Text + a;
textBox1.AppendText(Environment.NewLine);
}
}
}
}
Renas Rajab Rekany OOP 2018
39
Example 2:
OUTPUT
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i,j;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
textBox1.Text = textBox1.Text + i+j+" ";
textBox1.AppendText(Environment.NewLine);
}
}
}
}
H.W) Find the main diagonal, secondary diagonal, swap the rows to columns…
Renas Rajab Rekany OOP 2018
40
2.2 While Loop:
Example 3:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int num, r, i;
num = Convert.ToInt32(textBox1.Text);
i = 1;
while (i <= 10)
{
Renas Rajab Rekany OOP 2018
41
r = num * i;
textBox2.Text = textBox2.Text + r + "=" + num + "*" + i;
textBox2.AppendText(Environment.NewLine);
i += 1;
}
}
}
}
2.3 Do-While Loop:
Note: must put semi-colon(;) at the end of while condition in do-while loop.
Example 4:
private void button1_Click(object sender, EventArgs e)
{
int num, r, i;
num = Convert.ToInt32(textBox1.Text);
i = 1;
do
{
r = num * i;
textBox2.Text = textBox2.Text + r + "=" + num + "*" + i;
textBox2.AppendText(Environment.NewLine);
i += 1;
} while (i <= 10);
}
Q) What's the different between the (While and Do_While loop)?
Renas Rajab Rekany OOP 2018
42
Break:
The break is use in for, while, do-while, switch case. Break statement is used to
terminating the current flow of program and transfer controls to the next execution.
Continue:
The continue is use in for, while, do-while. The continue statements enables you to
skip the loop and jump the loop to next iteration.
continue break
for (int i=0;i<=5;i++)
{
if(i<=3)
continue ;
textBox1.Text = textBox1.Text + i;
textBox1.AppendText(Environment.NewLine);
}
4
5
for (int j = 0; j <= 5; j++)
{
if (j >= 3)
break ;
textBox2.Text = textBox2.Text + j;
textBox2.AppendText(Environment.NewLine);
}
0
1
2
EX:
Break
for (int i=1; i<=7;i++)
{
If (i==5)
Break;
Textbox1.text=textbox1.text+ i;
}
Output
1 2 3 4
Continue
Renas Rajab Rekany OOP 2018
43
For (int i=1; i<=7;i++)
{ if (i==5)
Continue;
Textbox1.text=textbox1.text+ i;
}
Output
1234 678910
Build_in and User_define C# Methods
1- Method (= Function)
A method is a group of statements that together perform a task. It combines related code together and
makes program easier. Every C# program has at least one class with a method named Main.
2- Method Types:
1. Built in: the methods that the language provides. Such as Math class provide the following
methods:
Abs (x) exp (x) tan (x)
Cos (x) pow (x,y) log (x)
Sin (x) max (x,y) Sqrt (x)
Log10, max, min, round, sqrt.
Example:
Math.abs(x);
Textbox1.text=Convert.ToString(math.abs(-10));
Math.cos(x);
Renas Rajab Rekany OOP 2018
44
2. User defines: the methods that the user defines and call.
Example:
int sum (int x , int y)
{int s=x+y;
Return (s);}
3- Defining Methods in C# and calling techniques:
When you define a method, you basically declare the elements of its structure. The syntax for
defining a method in C# is as follows:
Following are the various elements of a method:
• Access Specifier: This determines the visibility of a variable or a method from
another class.
• Return type: A method may return a value. The return type is the data type of the
value the method returns. If the method is not returning any values, then the return
type is void.
• Method name: Method name is a unique identifier and it is case sensitive. It
cannot be same as any other identifier declared in the class.
• Parameter list: Enclosed between parentheses, the parameters are used to pass
and receive data from a method. The parameter list refers to the type, order, and
number of the parameters of a method. Parameters are optional; that is, a method
may contain no parameters.
< Access Specifier> < Return Type> < Method Name> (Parameter list)
{
Body
}
Renas Rajab Rekany OOP 2018
45
• Method body: This contains the set of instructions needed to complete the
required activity.
Example:
public void add()
{
Body
}
In the preceding example, the public is an access specifier, void is a return data type
that return nothing and add() is a method name. There is no parameter define in
add() method.
If the function returns interger value, then you can define function as follow:
public int add()
{
Body
}
If the function is returning string value, then you can define function as follow:
public string printname()
{
Body
}
You must remember, whenever use return data type with method, must return value
using return keyword from body. If you don’t want to return any value, then you can
use void data type.
Renas Rajab Rekany OOP 2018
46
Ex:
Class program
{
public int sqr(int a)
{
return (a * a);
}
private void button1_Click(object sender, EventArgs e)
{
int b;
b =Convert.ToInt32( textBox1.Text);
textBox2.Text = Convert.ToString(sqr(b));
}
}
4- Passing arguments:
pass by value Pass by reference
static int sqr(int x)
{
return ( x * x);
} ----------
Output
- Before call x is 5
- After call x is 5
static int sqr2(ref int x)
{
return x * x;
}
----------
Output
- Before call x is 5
- After call x is 25
Renas Rajab Rekany OOP 2018
47
Method overload
1. C# enable several methods of same name to be defined in same class as long as
these method have different sets of parameters (number of parameter , type of
parameter , order of parameter ) this is called method overloaded .
2. Method overloading commonly is used to create several methods with same name
that perform similar tasks, but on different data types.
Ex:
Static int squire (int x)
{
return (x*x);
}
Static double squire (double x)
{
return (x*x);
}
static void main ( )
{
int y = 2;
double z=12.1;
textBox1.Text = Convert.ToString(squire(y));
textBox1.Text = Convert.ToString(squire(z));
}
Output
- The squire of int 2 is 4.
- The squire of double 2.1 is 4.41.
Note: This is called overload method.
Renas Rajab Rekany OOP 2018
48
Arrays (declaration 1_D, 2_D, initialization)
1- Array:
Sometimes, you need to declare multiple variable of same data type. It is complex
and time consuming process. Just for an example, you have to declare 100 integer
type of variable then what would you do? Will you declare variable as follow:
int num1,num2,num3,num4,num5,num6,num7,num8.... num100;
It is not a suitable way to declare multiple variable of same data type. To overcome
this situation, array came alive. An array is a collection of same data type. If you
have to declare 100 variable of same data type in C#, then you can declare and
initialize an array as follow.
int[] num = new int[100];
2- Structure of C# array:
To understand concept of array, consider the following example. What happens in
memory when we declare an integer type array?
int[] num = new int[6];
Num Array:
Renas Rajab Rekany OOP 2018
49
3- Declaration and Initialization of Array:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int[] array=new int [5];
array[0] = 3;
array[1] = 6;
array[2] = 2;
array[3] = 7;
array[4] = 9;
for (int i = 0; i < 5; i++)
{
textBox1.Text = textBox1.Text + array[i];
textBox1.AppendText(Environment.NewLine);
}
}
}
}
Renas Rajab Rekany OOP 2018
50
4- Storing value directly in C# program:
In your program, you can directly store value in array. You can store value in array
by two ways.
i. Inline:
int[] arr =new int[5] { 3, 6, 2, 7, 9 };
ii. Index:
int[] arr = new int[5]
arr[0] = 3;
arr[1] = 6;
arr[2] = 2;
arr[3] = 7;
arr[4] = 9;
iii. Users input:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Renas Rajab Rekany OOP 2018
51
private void button1_Click(object sender, EventArgs e)
{
int[] array2 = new int[10];
for (int i = 0; i < 10; i++)
{
array2[i] = Convert.ToInt32(Interaction.InputBox("Enter The
array elements", "Input Box", "Write Here", 75, 75));
textBox1.Text = textBox1.Text + array2[i];
textBox1.AppendText(Environment.NewLine);
}
}
}
}
Hint: To define InputBox, you have to Add reference from .Net-> Microsoft.Visual Basic,
then write it's library.
Renas Rajab Rekany OOP 2018
52
5- Accessing value from array:
You can access array’s value by its index position. Each index position in array
refers to a memory address in which your values are saved.
int[] arr=new int[6];
int num1, num2;
num1 = arr[1] * arr[3];
It is same as:
num1 = 23 * 9; Because, arr[1] refers to the value 23 and arr[3] refers to the value 9.
If you are required to access entire value of an array one after another, then you can
use loop constructs to iterate through array.
Example3:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Renas Rajab Rekany OOP 2018
53
private void button1_Click(object sender, EventArgs e)
{
int[] id = new int[3];
string[] name = new string[3];
int i, j = 0;
string f;
for (i = 0; i < 3; i++)
{
id[i] = Convert.ToInt32(Interaction.InputBox("Enter the id",
"InputBox", "Enter Here", 75, 75));
name[i] = Interaction.InputBox("Enter the name", "InputBox",
"Enter Here", 75, 75);
}
f = Interaction.InputBox("Enter the name to find", "InputBox",
"Enter Here", 75, 75);
for (i = 0; i < 3; i++)
{
if (name[i] == f)
{
MessageBox.Show(Convert.ToString(id[i]), "The Id is:");
j++;
}
}
if (j == 0)
MessageBox.Show("Not Found");
}
}
}
Hint: To define InputBox, you have to Add reference from .Net-> Microsoft. Visual Basic,
then write it's library.
Renas Rajab Rekany OOP 2018
54
Array dimensions
A. One dimensional:
The one dimensional array or single dimensional array in C# is the simplest type of
array that contains only one row for storing data. It has single set of square bracket
(“[]”). To declare single dimensional array in C#, you can write the following code.
Example4:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Renas Rajab Rekany OOP 2018
55
string[] books = new string[5] { "C#", "VB", "JAVA", "C++", "MATLAB"
};
textBox1.Text = "First Second Third Four Five";
textBox1.AppendText(Environment.NewLine);
textBox1.Text = textBox1.Text + "_______________________________";
textBox1.AppendText(Environment.NewLine);
for (int i = 0; i < 5; i++)
{
textBox1.Text = textBox1.Text + books[i] + " ";
}
}
}
}
OUTPUT:
B. Multi-dimensional array:
The multi-dimensional array in C# is such type of array that contains more than one
row to store data on it. The multi-dimensional array is also known as rectangular array
in c sharp because it has same length of each row. It can be two dimensional array or
three dimensional array or more. It contains more than one coma (,) within single
rectangular brackets (“[ , , ,]”). To storing and accessing the elements from
Renas Rajab Rekany OOP 2018
56
multidimensional array, you need to use nested loop in program. The following
example will help you to figure out the concept of multidimensional array.
Example5:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Renas Rajab Rekany OOP 2018
57
string[,] books = new string[3,3]{ { "C#", "VB", "JAVA"},{".NET",
"C++", "DB" },{"SQL","HTML","XML"}};
textBox1.Text = "First Second Third ";
textBox1.AppendText(Environment.NewLine);
textBox1.Text = textBox1.Text + "___________________________";
textBox1.AppendText(Environment.NewLine);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
textBox1.Text = textBox1.Text + books[i, j] + " ";
}
textBox1.AppendText(Environment.NewLine);
}
}
}
}
OUTPUT:
Renas Rajab Rekany OOP 2018
58
Passing array
An array can also be passed to method as argument or parameter. A method process
the array and returns output. Passing array as parameter in C# is pretty easy as passing
other value as parameter. Just create a function that accepts array as argument and then
process them. The following demonstration will help you to understand how to pass
array as argument in C# programming.
Example4:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void printarray(int[] print)
{
int i;
for (i = 0; i < 5; i++)
{
textBox1.Text = textBox1.Text + print[i];
textBox1.AppendText(Environment.NewLine);
}
}
private void button1_Click(object sender, EventArgs e)
{
int[] num = new int[5] { 2, 4, 6, 8, 10 };
printarray(num);
}
} }
Renas Rajab Rekany OOP 2018
59
Most common properties of Array class
Properties Explanation Example
Length Returns the length of array. Returns integer value. int i = arr1.Length;
Rank
Returns total number of items in all the dimension. Returns
integer value.
int i = arr1.Rank;
IsFixedSize
Check whether array is fixed size or not. Returns Boolean
value
bool i = arr.IsFixedSize;
IsReadOnly
Check whether array is ReadOnly or not. Returns Boolean
value
bool k =
arr1.IsReadOnly;
H.M) Apply these properties in arrays (Max, Min, Sum, Average, First, Last).
Most common functions of Array class
Function Explanation Example
Sort Sort an array Array.Sort(arr);
Clear Clear an array by removing all the items Array.Clear(arr, 0, 3);
GetLength Returns the number of elements arr.GetLength(0);
GetValue Returns the value of specified items arr.GetValue(2);
IndexOf Returns the index position of value Array.IndexOf(arr,45);
Copy Copy array elements to another elements Array.Copy(arr1,arr1,3);
Example5:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
Renas Rajab Rekany OOP 2018
60
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void arr_mul(int[] array1)
{
int i;
double mul = 1;
for (i = 0; i < 5; i++)
{
textBox8.Text = textBox8.Text + array1[i];
mul *= array1[i];
}
for (i = 0; i < 5; i++)
{
textBox9.Text = textBox9.Text+array1[i].ToString();
}
Array.Sort(array1);
for(i=0;i<5;i++)
{
textBox6.Text = textBox6.Text + array1[i].ToString();
}
textBox11.Text = mul.ToString() ;
}
private void button1_Click(object sender, EventArgs e)
{
int[] arr1 = new int[5] { 7, 3, 12, 8, 11 };
int[] arr2 = new int[5];
int len, r,gl,gt;
bool fixedsize, read_only;
Array.Copy(arr1, arr2, arr1.Length);
len = arr1.Length;
textBox1.Text = len.ToString();
r=arr1.Rank;
textBox2.Text = r.ToString();
Renas Rajab Rekany OOP 2018
61
fixedsize = arr1.IsFixedSize;
textBox3.Text = fixedsize.ToString();
read_only = arr1.IsReadOnly;
textBox4.Text = read_only.ToString();
gl=arr1.GetLength(0);
textBox5.Text = gl.ToString();
textBox10.Text = arr1.Sum().ToString();
gt=Convert.ToInt32(textBox7.Text);
textBox8.Text = arr1.GetValue(gt).ToString();
arr_mul(arr1);
}
}
}
Q) Write a program in C# to find the following in array, (Copy, Reverse, Find, Resize).
Renas Rajab Rekany OOP 2018
62
Events
TextBox lets users type letters and enter data. It is part of the Windows Forms platform
and is used with C# code. It is added with the Visual Studio designer. Many events and
properties are available on this control.
Intro. First, the TextBox will take care of reading the keys and displaying the text. But
it will not do anything with the text it accepts. You will need to access the text from the
TextBox based on custom logic rules.
Events. In Visual Studio the lightning bolt symbol describes event handlers. Windows
Forms programs are primarily event-based, which means you can use the lightning bolt
icon in the Properties dialog to add the most important event handlers.
Renas Rajab Rekany OOP 2018
63
TextChanged. You can use the TextChanged event to modify another part of your
program when the user types text into a TextBox. The TextChanged event is only
triggered when the text is changed to something different, not changed to the same
value.
This program assigns the base window's title text to the text typed in by the user to the
TextBox. This makes the base window's title reflect the user's input. The Windows
taskbar will also show this text.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//
// This changes the main window text when you type into the TextBox.
//
this.Text = textBox1.Text;
}
}
}
Renas Rajab Rekany OOP 2018
64
KeyDown. You can read key down events in the TextBox control in Windows Forms.
The Windows Forms system provides several key-based events. This tutorial uses the
KeyDown event handler which is called before the key value actually is painted.
You can cancel the key event in the KeyDown event handler as well, although this is
not demonstrated. The program will display an alert when the Enter key is pressed. An
alternative alert message when the Escape key is pressed.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
//
// Detect the KeyEventArg's key enumerated constant.
//
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("You pressed enter! Good job!");
}
else if (e.KeyCode == Keys.Escape)
{
MessageBox.Show("You pressed escape! What's wrong?");
}
}
}
}
Renas Rajab Rekany OOP 2018
65
Multiline. You can use the Multiline property on the TextBox control to create a longer
text input area. The TextBox control has performance problems with large amounts of
text. But for shorter multiline input boxes, this is useful.
Using TextBox with button. The screenshot shows a TextBox that was modified in the designer to
have its multiline property set to true. The form also has a Button control with the text "Save" on it.
Files. You can make the TextBox control do something that could be useful in a real program:
write the file to disk. This is essentially a primitive word processor. But don't use it to write
anything important yet.
After adding the multiline TextBox, we can add a Button and add the button1_Click event
handler. In that event handler, we can access the TextBox Text property and write it to a location
on the hard disk.
Renas Rajab Rekany OOP 2018
66
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//
// This is the button labeled "Save" in the program.
//
File.WriteAllText("C:demo.txt", textBox1.Text);
}
}
}
Result
This is some text
written for the textbox tutorial
The example calls the File.WriteAllText method. This method will take the string data
pointed to by the string reference returned by the Text property. It then actually writes
that to the physical hard disk on the computer.
TextBox.AppendText. TextBox provides the AppendText method. This method
appends lines of text to a TextBox control. With it we have to deal with newlines and
avoid extra line breaks. We are using the TextBox in multiline mode.
Example. We can append text to a TextBox with the method AppendText. However,
that will not append a newline or line feed to the end of the text, so when you call
textBox1.AppendText("text") two times, the text will be on the same line.
private void Test()
{
for (int i = 0; i < 2; i++)
{
textBox1.AppendText("Some text");
}
}
Renas Rajab Rekany OOP 2018
67
Example 2. You can append lines by using Environment.NewLine and then adding
some conditional logic to determine the first and last lines. This is better than any
version of AppendLine or AppendText. It doesn't add extra newlines.
public partial class Form1 : Form
{
private void AppendTextBoxLine(string myStr)
{
if (textBox1.Text.Length > 0)
{
textBox1.AppendText(Environment.NewLine);
}
textBox1.AppendText(myStr);
}
private void TestMethod()
{
for (int i = 0; i < 2; i++)
{
AppendTextBoxLine("Some text");
}
}
}
Contents of TextBox
Some text
Some text
Example 3. If you don't check the length of the Text in the TextBox, you will have
unwanted line breaks in your TextBox. However, for less important code, you may
prefer the slightly simpler method. The following code always appends newlines.
public partial class Browser : Form
{
private void Test()
{
// Will leave a blank line on the end.
for (int i = 0; i < 2; i++)
{
textBox1.AppendText("Some text" + Environment.NewLine);
}
// Will leave a blank line on the start.
for (int i = 0; i < 2; i++)
{
textBox1.AppendText(Environment.NewLine + "Some text");
}
} }
Renas Rajab Rekany OOP 2018
68
ListBox stores several text items. It can interact with other controls, including Button
controls. We use this control in Windows Forms. In the example program it interacts
with two Buttons—through the Button Click event handler.
Tutorial. First, create a new Windows Forms C# project, and then open the Toolbox
and double-click on the ListBox item. This will insert a new ListBox into your Windows
Forms designer. If you want to use Buttons with the ListBox, add those too.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
List<string> _items = new List<string>(); // <-- Add this
public Form1()
{
InitializeComponent();
_items.Add("One"); // <-- Add these
_items.Add("Two");
_items.Add("Three");
listBox1.DataSource = _items;
}
}
}
Renas Rajab Rekany OOP 2018
69
In this example, we see a List of strings at the class level. This is a good place to store
the lines you want to show in your ListBox. In the constructor, we add three elements to
the List.
DataSource:At the final point in the constructor, we assign the DataSource from the
listBox1 to the new List.
Button. Go back to your Designer window in Visual Studio where you see the image of
the Form. Select the buttons and then add the text "Add" and "Remove" to their Text
properties in the Properties pane.
Add event handlers. Here we double-click on each button in the Designer. You will be
taken to the C# code view and a new event handler will have been inserted. In these
event handlers, we manipulate the List and refresh the ListBox.
private void button1_Click(object sender, EventArgs e)
{
// The Add button was clicked.
_items.Add("New item " + DateTime.Now.Second); // <-- Any string you want
// Change the DataSource.
listBox1.DataSource = null;
listBox1.DataSource = _items;
}
private void button2_Click(object sender, EventArgs e)
{
// The Remove button was clicked.
int selectedIndex = listBox1.SelectedIndex;
try
{
// Remove the item in the List.
_items.RemoveAt(selectedIndex);
}
catch
{
}
listBox1.DataSource = null;
listBox1.DataSource = _items;
}
Renas Rajab Rekany OOP 2018
70
Form. Here we see the complete code for the Form.cs file, which acts on the ListBox
and two Buttons in the Designer. It shows how to add and remove items to the ListBox
with the buttons.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
List<string> _items = new List<string>();
public Form1()
{
InitializeComponent();
_items.Add("One");
_items.Add("Two");
_items.Add("Three");
listBox1.DataSource = _items;
}
private void button1_Click(object sender, EventArgs e)
{
// The Add button was clicked.
_items.Add("New item " + DateTime.Now.Second);
// Change the DataSource.
listBox1.DataSource = null;
listBox1.DataSource = _items;
}
private void button2_Click(object sender, EventArgs e)
{
// The Remove button was clicked.
int selectedIndex = listBox1.SelectedIndex;
try
{
// Remove the item in the List.
_items.RemoveAt(selectedIndex);
}
catch
{
}
listBox1.DataSource = null;
Renas Rajab Rekany OOP 2018
71
listBox1.DataSource = _items;
}
}
}
Enabled. You can easily change the Enabled state of your Add and Remove buttons by
setting the Enabled property equal to false or true when the List is full or empty. This
example demonstrates setting Enabled.
private void button1_Click(object sender, EventArgs e)
{
// The Add button was clicked.
// ...
button2.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
// The Remove button was clicked.
// ....
if (listBox1.Items.Count == 0)
{
button2.Enabled = false;
}
}
In this example, there are two button click event handlers. Button1 is the Add button,
so it always sets the Enabled property of Add to true. Button2 is the Remove button, so
it is disabled when there are no items in the ListBox.
ComboBox is a combination TextBox with a drop-down. Its drop-down list presents
preset choices. The user can type anything into the ComboBox. Alternatively, he or she
can select something from the list.
Example. To begin, please create a new Windows Forms application and add a
ComboBox to it. You can then right-click on the ComboBox and add the
SelectedIndexChanged and TextChanged event handlers in the Properties dialog.
This program shows how when you change the text by typing in the ComboBox or by
Renas Rajab Rekany OOP 2018
72
clicking on the list of Items, the event handlers are triggered. Please see the section on
the Items property before running the program.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int _selectedIndex;
string _text;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// Called when a new index is selected.
_selectedIndex = comboBox1.SelectedIndex;
Display();
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
// Called whenever text changes.
_text = comboBox1.Text;
Display();
}
void Display()
{
this.Text = string.Format("Text: {0};
SelectedIndex: {1}",_text,_selectedIndex);
}
}
}
Text. The Text property of the ComboBox functions much like the Text property of a
TextBox. If you assign to the Text property, the current value in the ComboBox will
change. You can also read the Text property and assign string variables to it.
Items. The Items property contains the strings that are found in the drop-down part of
the ComboBox. You can type the Items line-by-line into Visual Studio through the
Items dialog, or you can dynamically add them during runtime.
To add Items, call the Add method: use the syntax comboBox1.Add("Value"). You can
also Clear the ComboBox with Clear().
Renas Rajab Rekany OOP 2018
73
RadioButton allows distinct selection of several items. In each group of RadioButtons,
only one can be checked or selected. Conceptually, this control implements an exclusive
selection. CheckBoxes allow multiple selections at once.
Steps. To begin, you should make a new Windows Forms application in Visual Studio,
and then you can add GroupBox (or Panel) controls to it. In these controls, you can nest
RadioButton instances.
By using this nesting strategy , you can have multiple groups of RadioButtons on a
single form.
You may want to add the CheckedChanged event handler on your RadioButtons.
You can actually have all the RadioButtons point to the same CheckedChanged event
handler using the event window in Visual Studio.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
// Executed when any radio button is changed.
// ... It is wired up to every single radio button.
// Search for first radio button in GroupBox.
string result1 = null;
foreach (Control control in this.groupBox1.Controls)
{
if (control is RadioButton)
Renas Rajab Rekany OOP 2018
74
{
RadioButton radio = control as RadioButton;
if (radio.Checked)
{
result1 = radio.Text;
}
}
}
// Search second GroupBox.
string result2 = null;
foreach (Control control in this.groupBox2.Controls)
{
if (control is RadioButton)
{
RadioButton radio = control as RadioButton;
if (radio.Checked)
{
result2 = radio.Text;
}
}
}
this.Text = result1 + " " + result2;
}
}
}
In the example, we wired up all six RadioButtons to the
radioButton1_CheckedChanged event handler. Thus, whenever the user clicks or
changes the selection on the form, the above method will be executed.
ErrorProvider simplifies and streamlines error presentation. It is an abstraction that
shows errors on your form. It does not require a lot of work on your part. This is its key
feature.
Start. To start, please open the Toolbox pane in Visual Studio. Find and double-click on
the ErrorProvider icon. This will insert the errorprovider1 into the tray at the bottom of
the screen. You can change properties on the ErrorProvider instance by right-clicking on
it and selecting Properties.
Renas Rajab Rekany OOP 2018
75
Example. We start with the basics. We must activate the ErrorProvider in our Windows
Forms program. The ErrorProvider won't initiate any actions. It will be invoked through
other event handlers in the program.
In the example, we have a TextBox control and a TextChanged event handler on that
control. When the TextChanged event handler is triggered, we check to see if a digit
character is present.
If one is not, we activate an error through the ErrorProvider. Otherwise we clear the
ErrorProvider.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
// Determine if the TextBox has a digit character.
string text = textBox1.Text;
bool hasDigit = false;
foreach (char letter in text)
{
if (char.IsDigit(letter))
{
hasDigit = true;
break;
}
}
// Call SetError or Clear on the ErrorProvider.
if (!hasDigit)
{
errorProvider1.SetError(textBox1, "Needs to contain a digit");
}
else
{
errorProvider1.Clear();
}
}
}
}
Renas Rajab Rekany OOP 2018
76
Using SetError method. The first argument of SetError is the identifier of the TextBox
control. The second argument is the error message itself. The first argument tells the
ErrorProvider where to draw the error sign.
Using Clear method. It is also important that you use the Clear method when
appropriate. If a digit was located, we simply remove the error sign from the user
interface. This instantly tells our user that no error is still present.
StatusStrip. A StatusStrip displays window status. It is usually at the bottom of a
window. We use a ToolStripStatusLabel hyperlink in the C# Windows Forms status bar.
Intro. We see an example of StatusStrip in Windows Forms, with tips on how to use its
properties. We introduce some parts of the Windows Forms program.
Some notes. There are other controls such as LinkLabel that you can use for links. But
this article is about my favorite way, the hyperlink in the status bar.
StatusStrip. The StatusStrip is a control in your Toolbox in Visual Studio. Double click
on its icon and then it will appear in the tray at the bottom of the Visual Studio window.
Items:Select the status strip control on your form, and in the Properties pane look
through the entries there and select Items.
Labels:In the Items window you can add things to the StatusStrip. Add new
ToolStripStatusLabels and a hyperlink.
Steps. I will assume you already have a StatusStrip. There are a few important things.
All of the items will be squished to the left of the status strip by default.
We can change this, and right-align a label. Here are the steps required to configure the
StatusStrip.
Spring:To right-align things on a StatusStrip we add a "spring" in between the left and
right items.
First step. Please open the Items dialog in Visual Studio. On your StatusStrip, open the
Items Collection Editor dialog in the A-Z listing.
Second, add some items. Leave the Status Label dropdown selected and click on the
big Add button. You can also add other types of controls to your status strip here.
To add a hyperlink, you can use a regular status label. You can make it a hyperlink later.
Third, add a ToolStripStatusLabel with "Spring" set to true. Put it after the leftmost
(first) status item. Add another status label after it. This will right-align the third status
label.
On the right side of the Items Collection Editor dialog, you will see another grid list.
Scroll to Text and type in the text of your link. Set the IsLink property to true.
Hyperlink. Double-click on the ToolStripStatusLabel you want to turn into a hyperlink.
We must use the Click event handler to make the status item do something when it is
clicked.
Renas Rajab Rekany OOP 2018
77
Process:To start a web browser, we will need to use the Process.Start method in
System.Diagnostics.
In the new Click event handler, add the inner line here. You can directly access
System.Diagnostics.
private void toolStripStatusLabel_Click(object sender,EventArgs e)
{
// Launch any website.
// ... You should change the URL!
System.Diagnostics.Process.Start("http://www.any.com/");
}
Background Color and Foreground Color
You can set background color and foreground color through property window and
programmatically.
textBox1.BackColor = Color.Blue;
textBox1.ForeColor = Color.White;
Textbox BorderStyle
You can set 3 different types of border style for textbox, they are None, FixedSingle and
fixed3d.
textBox1.BorderStyle = BorderStyle.Fixed3D;
TextBox Events
Keydown event
You can capture which key is pressed by the user using KeyDown event
Renas Rajab Rekany OOP 2018
78
TextChanged Event
When user input or setting the Text property to a new value raises the TextChanged
event
Textbox Maximum Length
Sets the maximum number of characters or words the user can input into the text box
control.
textBox1.MaxLength = 40;
Textbox ReadOnly
When a program wants to prevent a user from changing the text that appears in a text
box, the program can set the controls Read-only property is to True.
textBox1.ReadOnly = true;
Multiline TextBox
You can use the Multiline and ScrollBars properties to enable multiple lines of text to be
displayed or entered.
textBox1.Multiline = true;
Textbox passowrd character
TextBox controls can also be used to accept passwords and other sensitive information.
You can use the PasswordChar property to mask characters entered in a single line
version of the control
textBox1.PasswordChar = '*';
The above code set the PasswordChar to * , so when the user enter password then it
display only * instead of typed characters.
Renas Rajab Rekany OOP 2018
79
How to Newline in a TextBox
You can add new line in a textbox using many ways.
textBox1.Text += "your text" + "rn";
or
textBox1.Text += "your text" + Environment.NewLine;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Width = 250;
textBox1.Height = 50;
textBox1.Multiline = true;
textBox1.BackColor = Color.Blue;
textBox1.ForeColor = Color.White;
textBox1.BorderStyle = BorderStyle.Fixed3D;
}
private void button1_Click(object sender, EventArgs e)
{
string var;
var = textBox1.Text;
MessageBox.Show(var);
}
}
}
You can use Regular Expression to validate a Textbox to enter number only.
System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[ ^ 0-9]")
Renas Rajab Rekany OOP 2018
80
The following method also you can force your user to enter numeric value only.
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
If you want to allow decimals add the following to the above code.
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
e.Handled = true;
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, " ^ [0-9]"))
{
textBox1.Text = "";
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
{
e.Handled = true;
}
}
}
}
Renas Rajab Rekany OOP 2018
81
C# ProgressBar Control
A progress bar is a control that an application can use to indicate the progress of a
lengthy operation such as calculating a complex result, downloading a large file from
the Web etc.
ProgressBar controls are used whenever an operation takes more than a short period of
time. The Maximum and Minimum properties define the range of values to represent the
progress of a task.
Minimum : Sets the lower value for the range of valid values for progress.
Maximum : Sets the upper value for the range of valid values for progress.
Value : This property obtains or sets the current level of progress.
By default, Minimum and Maximum are set to 0 and 100. As the task proceeds, the
ProgressBar fills in from the left to the right. To delay the program briefly so that you
can view changes in the progress bar clearly.
The following C# program shows a simple operation in a progressbar.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int i;
progressBar1.Minimum = 0;
progressBar1.Maximum = 200;
for (i = 0; i <= 200; i++)
Renas Rajab Rekany OOP 2018
82
{
progressBar1.Value = i;
}
}
}
}
C# DateTimePicker Control
The DateTimePicker control allows you to display and collect date and time from the
user with a specified format.
The DateTimePicker control has two parts, a label that displays the selected date and a
popup calendar that allows users to select a new date. The most important property of
the DateTimePicker is the Value property, which holds the selected date and time.
dateTimePicker1.Value = DateTime.Today;
The Value property contains the current date and time the control is set to. You can use
the Text property or the appropriate member of Value to get the date and time value.
DateTime iDate;
iDate = dateTimePicker1.Value;
Renas Rajab Rekany OOP 2018
83
The control can display one of several styles, depending on its property values. The
values can be displayed in four formats, which are set by the Format property: Long,
Short, Time, or Custom.
dateTimePicker1.Format = DateTimePickerFormat.Short;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dateTimePicker1.Format = DateTimePickerFormat.Short;
dateTimePicker1.Value = DateTime.Today;
}
private void button1_Click(object sender, EventArgs e)
{
DateTime iDate;
iDate = dateTimePicker1.Value;
MessageBox.Show("Selected date is " + iDate);
}
}
}
C# Menu Control
A Menu on a Windows Form is created with a MainMenu object, which is a collection
of MenuItem objects. MainMenu is the container for the Menu structure of the form and
menus are made of MenuItem objects that represent individual parts of a menu.
You can add menus to Windows Forms at design time by adding the MainMenu
component and then appending menu items to it using the Menu Designer.
Renas Rajab Rekany OOP 2018
84
After drag the Menustrip on your form you can directly create the menu items by type a
value into the "Type Here" box on the menubar part of your form. If you need a
seperator bar , right click on your menu then go to insert->Seperator.
Renas Rajab Rekany OOP 2018
85
After creating the Menu on the form , you have to double click on each menu item and
write the programs there depends on your requirements. The following C# program
shows how to show a messagebox when clicking a Menu item.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void menu1ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("You are selected MenuItem_1");
}
}
}
C# Color Dialog Box
There are several classes that implement common dialog boxes, such as color selection ,
print setup etc.
A ColorDialog object is a dialog box with a list of colors that are defined for the display
system. The user can select or create a particular color from the list, which is then
Renas Rajab Rekany OOP 2018
86
reported back to the application when the dialog box exits. You can invite a color dialog
box by calling ShowDialog() method.
ColorDialog dlg = new ColorDialog();
dlg.ShowDialog();
The following C# program invites a color dialog box and retrieve the selected color to a
string.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ColorDialog dlg = new ColorDialog();
dlg.ShowDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
string str = null;
str = dlg.Color.Name;
MessageBox.Show (str);
}
}
}
}
C# Font Dialog Box
Font dialog box represents a common dialog box that displays a list of fonts that are
currently installed on the system. The Font dialog box lets the user choose attributes for
a logical font, such as font family and associated font style, point size, effects , and a
script.
Renas Rajab Rekany OOP 2018
87
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FontDialog dlg = new FontDialog();
dlg.ShowDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
string fontName;
float fontSize;
fontName = dlg.Font.Name;
fontSize = dlg.Font.Size;
MessageBox.Show(fontName + " " + fontSize );
}
}
}
}
Renas Rajab Rekany OOP 2018
88
C# OpenFile Dialog Box
The OpenFileDialog component allows users to browse the folders of their computer or
any computer on the network and select one or more files to open. The dialog box
returns the path and name of the file the user selected in the dialog box.
The FileName property can be set prior to showing the dialog box. This causes the
dialog box to initially display the given filename. In most cases, your applications
should set the InitialDirectory, Filter, and FilterIndex properties prior to calling
ShowDialog.
The following C# program invites an OpenFile Dialog Box and retrieve the selected
filename to a string.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.ShowDialog();
if (dlg.ShowDialog() == DialogResult.OK)
Renas Rajab Rekany OOP 2018
89
{
string fileName;
fileName = dlg.FileName;
MessageBox.Show(fileName);
}
}
}
}
C# Print Dialog Box
A user can use the Print dialog box to select a printer, configure it, and perform a print
job. Print dialog boxes provide an easy way to implement Print and Print Setup dialog
boxes in a manner consistent with Windows standards.
The Print dialog box includes a Print Range group of radio buttons that indicate whether
the user wants to print all pages, a range of pages, or only the selected text. The dialog
box includes an edit control in which the user can type the number of copies to print. By
default, the Print dialog box initially displays information about the current default
printer.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Win
dowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
Renas Rajab Rekany OOP 2018
90
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
PrintDialog dlg = new PrintDialog();
dlg.ShowDialog();
}
}
}
C# Label Control
Labels are one of the most frequently used C# control. We can use the Label control to
display text in a set location on the page. Label controls can also be used to add
descriptive text to a Form to provide the user with helpful information. The Label class
is defined in the System.Windows.Forms namespace.
Add a Label control to the form - Click Label in the Toolbox and drag it over the forms
Designer and drop it in the desired location.
If you want to change the display text of the Label, you have to set a new text to the
Text property of Label.
label1.Text = "This is my first Label";
In addition to displaying text, the Label control can also display an image using the
Image property, or a combination of the ImageIndex and ImageList properties.
label1.Image = Image.FromFile("C:testimage.jpg");
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Renas Rajab Rekany OOP 2018
91
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "This is my first Lable";
label1.BorderStyle = BorderStyle.FixedSingle;
label1.TextAlign = ContentAlignment.MiddleCenter;
}
}
}
C# Button Control
Windows Forms controls are reusable components that encapsulate user interface
functionality and are used in client side Windows applications. A button is a control,
which is an interactive component that enables users to communicate with an
application. The Button class inherits directly from the ButtonBase class. A Button can
be clicked by using the mouse, ENTER key, or SPACEBAR if the button has focus.
When you want to change display text of the Button , you can change the Text property
of the button.
button1.Text = "Click Here";
Similarly if you want to load an Image to a Button control , you can code like this
button1.Image = Image.FromFile("C:testimage.jpg");
How to Call a Button's Click Event Programmatically
The Click event is raised when the Button control is clicked. This event is commonly
used when no command name is associated with the Button control. Raising an event
invokes the event handler through a delegate.
private void Form1_Load(object sender, EventArgs e)
{
Button b = new Button();
b.Click += new EventHandler(ShowMessage);
Controls.Add(b);
}
private void ShowMessage(object sender, EventArgs e)
{
MessageBox.Show("Button Click");
}
Renas Rajab Rekany OOP 2018
92
C# MDI Form
A Multiple Document Interface (MDI) programs can display multiple child windows
inside them. This is in contrast to single document interface (SDI) applications, which
can manipulate only one document at a time. Visual Studio Environment is an example
of Multiple Document Interface (MDI) and notepad is an example of an SDI application.
MDI applications often have a Window menu item with submenus for switching
between windows or documents.
Any windows can become an MDI parent, if you set the IsMdiContainer property to
True.
IsMdiContainer = true;
The following C# program shows a MDI form with two child forms. Create a new C#
project, then you will get a default form Form1 . Then add two mnore forms in the
project (Form2 , Form 3) . Create a Menu on your form and call these two forms on
menu click event.
NOTE: If you want the MDI parent to auto-size the child form you can code like this.
Renas Rajab Rekany OOP 2018
93
form.MdiParent = this;
form.Dock=DockStyle.Fill;
form.Show();
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
IsMdiContainer = true;
}
private void menu1ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show();
frm2.MdiParent = this;
}
private void menu2ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 frm3 = new Form3();
frm3.Show();
frm3.MdiParent = this;
}
}
}
keyPress event in C#
Handle Keyboard Input at the Form Level in C#
Windows Forms processes keyboard input by raising keyboard events in response to
Windows messages. Most Windows Forms applications process keyboard input
exclusively by handling the keyboard events.
How do I detect keys pressed in C#
You can detect most physical key presses by handling the KeyDown or KeyUp events.
Key events occur in the following order:
Renas Rajab Rekany OOP 2018
94
KeyDown
KeyPress
KeyUp
How to detect when the Enter Key Pressed in C#
The following C# code behind creates the KeyDown event handler. If the key that is
pressed is the Enter key, a MessegeBox will displayed .
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter Key Pressed ");
}
How to get TextBox1_KeyDown event in your C# source file ?
Select your TextBox control on your Form and go to Properties window. Select Event
icon on the properties window and scroll down and find the KeyDown event from the
list and double click the Keydown Event. The you will get the KeyDown event in your
source code editor.
private void textBox1_KeyDown(.....)
{
}
Renas Rajab Rekany OOP 2018
95
Difference between the KeyDown Event, KeyPress Event and KeyUp Event
KeyDown Event : This event raised as soon as the user presses a key on the keyboard,
it repeats while the user keeps the key depressed.
KeyPress Event : This event is raised for character keys while the key is pressed and
then released. This event is not raised by noncharacter keys, unlike KeyDown and
KeyUp, which are also raised for noncharacter keys
KeyUp Event : This event is raised after the user releases a key on the keyboard.
KeyPress Event :
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
MessageBox.Show("Enter key pressed");
}
if (e.KeyChar == 13)
{
MessageBox.Show("Enter key pressed");
}
}
}
}
KeyDown Event :
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Renas Rajab Rekany OOP 2018
96
MessageBox.Show("Enter key pressed");
}
}
}
}
How to Detecting arrow keys in C#
In order to capture keystrokes in a Forms control, you must derive a new class that is
based on the class of the control that you want, and you override the ProcessCmdKey().
KeyUp Event :
The following C# source code shows how to capture Enter KeyDown event from a
TextBox Control.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter key pressed");
}
}
}
}
How to create Dynamic Controls in C# ?
How to create Control Arrays in C# ?
Visual Studio .NET does not have control arrays like Visual Basic 6.0 does. The good
news is that you can still set things up to do similar things. The advantages of C#
dynamic controls is that they can be created in response to how the user interacts with
the application. Common controls that are added during run-time are the Button and
TextBox controls. But of course, nearly every C# control can be created dynamically.
Renas Rajab Rekany OOP 2018
97
How to create Dynamic Controls in C# ?
The following program shows how to create a dynamic TextBox control in C# and
setting the properties dynamically for each TextBox control. Drag a Button control in
the form and copy and paste the following source code.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int cLeft = 1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
AddNewTextBox();
}
public System.Windows.Forms.TextBox AddNewTextBox()
{
System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox();
this.Controls.Add(txt);
txt.Top = cLeft * 25;
txt.Left = 100;
txt.Text = "TextBox " + this.cLeft.ToString();
cLeft = cLeft + 1;
return txt;
}
}
}
Renas Rajab Rekany OOP 2018
98
Keep Form on Top of All Other Windows
The System.Windows.Forms namespace contains classes for creating Windows-based
applications that take full advantage of the rich user interface features available in the
Microsoft Windows operating system. You can bring a Form on top of application by
simply setting the Form.topmost form property to true will force the form to the top
layer of the screen, while leaving the user able to enter data in the forms below.
Form2 frm = new Form2();
frm.TopMost = true;
frm.Show();
Topmost forms are always displayed at the highest point in the z-order of the windows
on the desktop. You can use this property to create a form that is always displayed in
your application, such as a MessageBox window.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.TopMost = true;
frm.Show();
}
}
}
Renas Rajab Rekany OOP 2018
99
C# Timer Control
What is Timer Control ?
The Timer Control plays an important role in the development of programs both Client
side and Server side development as well as in Windows Services. With the Timer
Control we can raise events at a specific interval of time without the interaction of
another thread.
Use of Timer Control
We require Timer Object in many situations on our development environment. We have
to use Timer Object when we want to set an interval between events, periodic checking,
to start a process at a fixed time schedule, to increase or decrease the speed in an
animation graphics with time schedule etc.
A Timer control does not have a visual representation and works as a component in the
background.
How to Timer Control ?
We can control programs with Timer Control in millisecond, seconds, minutes and even
in hours. The Timer Control allows us to set Intervel property in milliseconds. That is,
one second is equal to 1000 milliseconds. For example, if we want to set an interval of 1
minute we set the value at Interval property as 60000, means 60x1000 .
By default the Enabled property of Timer Control is False. So before running the
program we have to set the Enabled property is True , then only the Timer Control starts
its function.
Renas Rajab Rekany OOP 2018
100
In the following program we display the current time in a Label Control. In order to
develop this program, we need a Timer Control and a Label Control. Here we set the
timer interval as 1000 milliseconds, that means one second, for displaying current
system time in Label control for the interval of one second.
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToString();
}
}
}
Start and Stop Timer Control
The Timer control have included the Start and Stop methods for start and stop the Timer
control functions.
Here we run this program only 10 seconds. In order to doing this ,in the following
program we set Timer interval as 1000 (1 second) and check each seconds for stopping
the Timer Control after 10 seconds.
Renas Rajab Rekany OOP 2018
101
Code
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
int second = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToString();
second = second + 1;
if (second >= 10)
{
timer1.Stop();
MessageBox.Show("Exiting from Timer....");
}
}
}
}
Renas Rajab Rekany OOP 2018
102
Object Oriented Programming
Structured programming is not the wrong way to write programs. Similarly, object-oriented
programming is not necessarily the right way. Object-oriented programming (OOP) is an
alternative program development technique that often tends to be better if we deal with large
programs and if we care about program reusability.
We make the following observations about structured programming:
- Structured programming is narrowly oriented towards solving one particular
problem
- It would be nice if our programming efforts could be oriented more broadly
- Structured programming is carried out by gradual decomposition of the functionality
- The structures formed by functionality/actions/control are not the most stable parts
of a program
- Focusing on data structures instead of control structure is an alternative approach
- Real systems have no single top - Real systems may have multiple tops [Bertrand
Meyer]
- It may therefore be natural to consider alternatives to the top-down approach
OOP Concepts
1. Data Abstraction – it is the act of representing the essential features without
including the background details. Data Hiding- it is a related concept of data abstraction.
Unessential features are hidden from the world.
2. Data Encapsulation – it is the wrapping of data and associated functions in one single unit.
3. Inheritance – it is the capability of one class to inherit properties from other class.
4. Polymorphism – it is the ability for data to be processed in more than one form.
5. Modularity – it is the concept of breaking down the program into several module. E.g. :
Classes, Structure, etc.
Renas Rajab Rekany OOP 2018
103
Class
Class: is an abstraction model used to define a new Data Type Which May Contain a Combination
of encapsulating Data (Member Variable) Operation That Can Be Perform On Data (Member
Function) And Accessory to Data (properties).
Member Variable = Field
Member Function = Method
Properties = Attributes
Declaration
Class Class_name
{
[Properties] Member Variable;
[Properties] Member Function;
.
.
.
}
Class_name var = new Class_name ();
❖ Class can declared before or after main method
❖ Or can be declared before class program.
❖ we can change class program to any name
What a class is
Classes are the user defined data types that represent the state and behaviour of an object. State
represents the properties and behaviour is the action that objects can perform.
Classes can be declared using the following access specifiers that limit the accessibility of classes
to other classes, however some classes does not require any access modifiers.
1. Public
2. Private
3. Protected
4. Internal
5. Protected internal
To learn the details of access specifiers please refer to the following article of mine:
• Access Modifiers in C#
Renas Rajab Rekany OOP 2018
104
For example:
public class Accounts
{
}
Some Key points about classes
• Classes are reference types that hold the object created dynamically in a heap.
• All classes have a base type of System.Object.
• The default access modifier of a class is Internal.
• The default access modifier of methods and variables is Private.
• Directly inside the namespaces declarations of private classes are not allowed.
The following are types of classes in C#:
What an Abstract class is
An Abstract class is a class that provides a common definition to the subclasses and this is the type
of class whose object is not created.
Some key points of Abstract classes are:
• Abstract classes are declared using the abstract keyword.
• We cannot create an object of an abstract class.
• If you want to use it then it must be inherited in a subclass.
• An Abstract class contains both abstract and non-abstract methods.
• The methods inside the abstract class can either have an implementation or no
implementation.
• We can inherit two abstract classes; in this case the base class method implementation is
optional.
• An Abstract class has only one subclass.
• Methods inside the abstract class cannot be private.
• If there is at least one method abstract in a class then the class must be abstract.
For example:
abstract class Accounts
{
}
Renas Rajab Rekany OOP 2018
105
Partial Classes
It is a type of class that allows dividing their properties, methods and events into multiple source
files and at compile time these files are combined into a single class.
The following are some key points:
• All the parts of the partial class must be prefixed with the partial keyword.
• If you seal a specific part of a partial class then the entire class is sealed, the same as for an
abstract class.
• Inheritance cannot be applied on partial classes.
• The classes that are written in two class files are combined together at run time.
For example:
partial class Accounts
{
}
Sealed Class
A Sealed class is a class that cannot be inherited and used to restrict the properties.
The following are some key points:
• A Sealed class is created using the sealed keyword.
• Access modifiers are not applied to a sealed class.
• To access the sealed members we must create an object of the class.
For example:
sealed class Accounts
{
}
Static Class
It is the type of class that cannot be instantiated, in oher words we cannot create an object of that
class using the new keyword, such that class members can be called directly using their class name.
The following are some key points:
• Created using the static keyword.
• Inside a static class only static members are allowed, in other words everything inside
thestatic class must be static.
• We cannot create an object of the static class.
• A Static class cannot be inherited.
• It allows only a static constructor to be declared.
Renas Rajab Rekany OOP 2018
106
• The methods of the static class can be called using the class name without creating the
instance.
For example:
static class Accounts
{
}
// Example 1
// Define Class point
class coordinate
{
public int x;
public int y;
public void setx(int a)
{ x = a; }
public void sety(int b)
{ y = b; }
public int getx()
{ return (x); }
public int gety()
{ return (y); }
}
// Calling the Class
private void button1_Click(object sender, EventArgs e)
{
coordinate p = new coordinate();
p.x = 10;
p.y = 5;
p.setx(6);
p.sety(7);
textBox1.Text = Convert.ToString(p.getx());
textBox2.Text = Convert.ToString(p.gety());
}
//Example 2
// Define Class circle
class circle
{
double radius;
double pi = 3.141;
public double area()
{ return (radius * radius * pi); }
public void set_r(double b)
Renas Rajab Rekany OOP 2018
107
{ radius = b; }
}
// Calling the Class
private void button1_Click(object sender, EventArgs e)
{
circle c = new circle();
double x = Convert.ToDouble(textBox1.Text);
c.set_r(x);
textBox2.Text=Convert.ToString( c.area());
}
//Example 3
// Class array Define and Sort
class sort
{
int[] ar = new int[10];
public void set_array(int[] a)
{ ar = a; }
public int[] get_array()
{ Array.Sort(ar); return ((ar)); }
}
// Calling the Class
private void button1_Click(object sender, EventArgs e)
{
sort s = new sort();
int[] b = new int[10] { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
s.set_array(b);
b=s.get_array();
for (int i = 0; i < 10; i++)
{ textBox1.Text = textBox1.Text + b[i]; }
}
Multi-Function in Class
//Example 4
//Class
class stage2
{ double fp = 1;
public double factx(int x)
{ for (int i = x; i > 0; i--)
{ fp = fp * i; }
return(fp); }
public double powx(int x,int y)
Renas Rajab Rekany OOP 2018
108
{ fp = Math.Pow(x, y);
return (fp); }
public string str_up(string a)
{return (a.ToUpper());}
public string str_dn(string a)
{return(a.ToLower());}
public string get_s;
public string set_s;
public void find_array(string[,] s)
{ for (int j = 0; j < 10; j++)
if (get_s == s[0, j])
{ set_s =s[2,j]+":"+s[0,j]+" = "+ s[1, j]; break; }
}
}
// Calling the Class from Button
private void button1_Click(object sender, EventArgs e)
{
string[,] st = new string[3, 10] { { "AA", "AB", "AC", "AD", “……..
stage2 s2 = new stage2();
if (comboBox1.Text == "factorial")
{ int x = Convert.ToInt32(textBox1.Text);
textBox2.Text = Convert.ToString(s2.factx(x));
}
else if (comboBox1.Text == "power")
{
int x = Convert.ToInt32(textBox1.Text);
textBox2.Text = Convert.ToString(s2.powx(x, x));
}
else if (comboBox1.Text == "upper")
{
string s = textBox1.Text;
textBox2.Text = s2.str_up(s);
}
else if (comboBox1.Text == "lower")
{
string s = textBox1.Text;
textBox2.Text = s2.str_dn(s);
}
else if (comboBox1.Text == "find")
{ s2.get_s = textBox3.Text;
s2.find_array(st);
textBox4.Text = s2.set_s;
} }
Renas Rajab Rekany OOP 2018
109
Constructor
Constructor: Is a special method used when an object of class is created, and is called automatically
in order to initialize a new instance of a class
Constructor properties
‽ Constructor has the same name of the class.
‽ Constructor does not return value.
‽ Constructor can be overloaded.
‽ Constructor has public access.
➢ Default Construction: has no parameters list.
➢ Parameter Construction: has parameters list.
➢ Copy Construction: has object parameter type.
//Example 5
//Class
class pickup
{ string model;
double speed;
public pickup() // Default Construction
{ model = ""; speed = 0; }
public pickup(string s, double d) // Parameter Construction
{ model = s; speed = d; }
public pickup(pickup k) // Copy Construction
{ model = k.model; speed = k.speed; } }
//Button
private void button1_Click(object sender, EventArgs e)
{ pickup c1 = new pickup(); // Default Construction
pickup c2 = new pickup("toyota", 220); // Parameter Construction
pickup c3 = new pickup(c2); // Copy Construction
}
Copy constructors: can be used for making copies of existing objects. A copy constructor can
be recognized by the fact that it takes a parameter of the same type as the class to which it belongs.
Object copying is an intricate matter, because we will have to decide if the referred object should
be copied too (shallow copying, deep copying, or something in between,
Renas Rajab Rekany OOP 2018
110
Destructor
Since C# is garbage collected, meaning that the framework will free the objects that you no longer
use, there may be times where you need to do some manual cleanup. A destructor, a method called
once an object is disposed, can be used to cleanup resources used by the object. Destructor doesn't
look very much like other methods in C#. Here is an example of a destructor for our Car class:
➢ Is a method called once an object is disposed, can be used to cleanup recourse used by the
object.
➢ Destructors only used with classes.
➢ A class can only have one destructor.
➢ Destructor cannot be inherited or overloaded.
➢ Destructor cannot be called, They are invoked automatically.
➢ Destructors cannot take a modifiers or have parameters.
~rain ()
{
MessageBox.Show("car object is dead");
}
//Example 6
//Class
class company
{ string model;
double speed;
public company() // Default Construction
{ model = ""; speed = 0; }
public company(string s, double d) // Parameter Construction
{ model = s; speed = d; }
public company(company k) // Copy Construction
{ model = k.model; speed = k.speed; }
public ~ company() // Destructor
{MessageBox.Show(" Destructor "); }
}
//Button
private void button1_Click(object sender, EventArgs e)
{ company c1 = new company(); // Default Construction
company c2 = new company("toyota", 220); // Parameter Construction
company c3 = new company(c2); // Copy Construction
}
Renas Rajab Rekany OOP 2018
111
Accessibility Keywords
All types and type members have an accessibility level, which controls whether they can be used
from other code in your assembly or other assemblies. You can use the following access modifiers
to specify the accessibility of a type or member when you declare it:
1. Public: The type or member can be accessed by any other code in the same assembly or
another assembly that references it.
2. Private: The type or member can be accessed only by code in the same class or structure.
3. Protected: The type or member can be accessed only by code in the same class or structure,
or in a class that is derived from that class.
4. Internal: The type or member can be accessed by any code in the same assembly, but not
from another assembly.
Public
The public keyword is an access modifier for types and type members. Public access is the most
permissive access level.
There are no restrictions on accessing public members.
Accessibility:
1. Can be accessed by objects of the class
2. Can be accessed by derived classes
Note: In the following example num1 is direct access.
//Example 7
//Class
class Program
{
class AccessMod
{
public int num1;
int num2;
}
//Button
private void button1_Click(object sender, EventArgs e)
{ AccessMod ob1 = new AccessMod();
C# with Renas
C# with Renas
C# with Renas
C# with Renas
C# with Renas
C# with Renas
C# with Renas
C# with Renas
C# with Renas
C# with Renas
C# with Renas
C# with Renas
C# with Renas
C# with Renas
C# with Renas
C# with Renas

Contenu connexe

Tendances

Cis 170 Extraordinary Success/newtonhelp.com
Cis 170 Extraordinary Success/newtonhelp.com  Cis 170 Extraordinary Success/newtonhelp.com
Cis 170 Extraordinary Success/newtonhelp.com amaranthbeg143
 
Cis 170 Education Organization -- snaptutorial.com
Cis 170   Education Organization -- snaptutorial.comCis 170   Education Organization -- snaptutorial.com
Cis 170 Education Organization -- snaptutorial.comDavisMurphyB99
 
MAX 2008 - Building your 1st AIR application
MAX 2008 - Building your 1st AIR applicationMAX 2008 - Building your 1st AIR application
MAX 2008 - Building your 1st AIR applicationrtretola
 
Cis 170 c Enhance teaching / snaptutorial.com
Cis 170 c  Enhance teaching / snaptutorial.comCis 170 c  Enhance teaching / snaptutorial.com
Cis 170 c Enhance teaching / snaptutorial.comHarrisGeorg51
 
CIS 170 Exceptional Education - snaptutorial.com
CIS 170   Exceptional Education - snaptutorial.comCIS 170   Exceptional Education - snaptutorial.com
CIS 170 Exceptional Education - snaptutorial.comDavisMurphyB33
 
Cis 170 Education Organization / snaptutorial.com
Cis 170 Education Organization / snaptutorial.comCis 170 Education Organization / snaptutorial.com
Cis 170 Education Organization / snaptutorial.comBaileya126
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsDigamber Singh
 
CIS 170 Life of the Mind/newtonhelp.com   
CIS 170 Life of the Mind/newtonhelp.com   CIS 170 Life of the Mind/newtonhelp.com   
CIS 170 Life of the Mind/newtonhelp.com   llflowe
 
Visual studio 2012
Visual studio 2012Visual studio 2012
Visual studio 2012Kiru Dennis
 
CIS 170 Education Specialist / snaptutorial.com
CIS 170  Education Specialist / snaptutorial.comCIS 170  Education Specialist / snaptutorial.com
CIS 170 Education Specialist / snaptutorial.comMcdonaldRyan138
 
Cis 170 i lab 1 of 7
Cis 170 i lab 1 of 7Cis 170 i lab 1 of 7
Cis 170 i lab 1 of 7helpido9
 
CIS 170 Inspiring Innovation/tutorialrank.com
 CIS 170 Inspiring Innovation/tutorialrank.com CIS 170 Inspiring Innovation/tutorialrank.com
CIS 170 Inspiring Innovation/tutorialrank.comjonhson110
 
A Lap Around Visual Studio 2010
A Lap Around Visual Studio 2010A Lap Around Visual Studio 2010
A Lap Around Visual Studio 2010Abram John Limpin
 
Csharp Hands On Lab Paul Yao
Csharp Hands On Lab Paul YaoCsharp Hands On Lab Paul Yao
Csharp Hands On Lab Paul YaoMamgmo Magnda
 

Tendances (18)

Intro to asp.net mvc 4 with visual studio
Intro to asp.net mvc 4 with visual studioIntro to asp.net mvc 4 with visual studio
Intro to asp.net mvc 4 with visual studio
 
Lvp jcreator
Lvp jcreatorLvp jcreator
Lvp jcreator
 
Cis 170 Extraordinary Success/newtonhelp.com
Cis 170 Extraordinary Success/newtonhelp.com  Cis 170 Extraordinary Success/newtonhelp.com
Cis 170 Extraordinary Success/newtonhelp.com
 
Cis 170 Education Organization -- snaptutorial.com
Cis 170   Education Organization -- snaptutorial.comCis 170   Education Organization -- snaptutorial.com
Cis 170 Education Organization -- snaptutorial.com
 
MAX 2008 - Building your 1st AIR application
MAX 2008 - Building your 1st AIR applicationMAX 2008 - Building your 1st AIR application
MAX 2008 - Building your 1st AIR application
 
Cis 170 c Enhance teaching / snaptutorial.com
Cis 170 c  Enhance teaching / snaptutorial.comCis 170 c  Enhance teaching / snaptutorial.com
Cis 170 c Enhance teaching / snaptutorial.com
 
CIS 170 Exceptional Education - snaptutorial.com
CIS 170   Exceptional Education - snaptutorial.comCIS 170   Exceptional Education - snaptutorial.com
CIS 170 Exceptional Education - snaptutorial.com
 
Cis 170 Education Organization / snaptutorial.com
Cis 170 Education Organization / snaptutorial.comCis 170 Education Organization / snaptutorial.com
Cis 170 Education Organization / snaptutorial.com
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
 
CIS 170 Life of the Mind/newtonhelp.com   
CIS 170 Life of the Mind/newtonhelp.com   CIS 170 Life of the Mind/newtonhelp.com   
CIS 170 Life of the Mind/newtonhelp.com   
 
Visual studio 2012
Visual studio 2012Visual studio 2012
Visual studio 2012
 
CIS 170 Education Specialist / snaptutorial.com
CIS 170  Education Specialist / snaptutorial.comCIS 170  Education Specialist / snaptutorial.com
CIS 170 Education Specialist / snaptutorial.com
 
Cis 170 i lab 1 of 7
Cis 170 i lab 1 of 7Cis 170 i lab 1 of 7
Cis 170 i lab 1 of 7
 
CIS 170 Inspiring Innovation/tutorialrank.com
 CIS 170 Inspiring Innovation/tutorialrank.com CIS 170 Inspiring Innovation/tutorialrank.com
CIS 170 Inspiring Innovation/tutorialrank.com
 
Visual c++ demo
Visual c++ demoVisual c++ demo
Visual c++ demo
 
Dvwkbm lab2 cli1
Dvwkbm lab2 cli1Dvwkbm lab2 cli1
Dvwkbm lab2 cli1
 
A Lap Around Visual Studio 2010
A Lap Around Visual Studio 2010A Lap Around Visual Studio 2010
A Lap Around Visual Studio 2010
 
Csharp Hands On Lab Paul Yao
Csharp Hands On Lab Paul YaoCsharp Hands On Lab Paul Yao
Csharp Hands On Lab Paul Yao
 

Similaire à C# with Renas

M365 global developer bootcamp 2019 PA
M365 global developer bootcamp 2019  PAM365 global developer bootcamp 2019  PA
M365 global developer bootcamp 2019 PAThomas Daly
 
Software Developer’s Project Documentation Template
Software Developer’s Project Documentation TemplateSoftware Developer’s Project Documentation Template
Software Developer’s Project Documentation TemplateSalim M Bhonhariya
 
Basic iOS Training with SWIFT - Part 4
Basic iOS Training with SWIFT - Part 4Basic iOS Training with SWIFT - Part 4
Basic iOS Training with SWIFT - Part 4Manoj Ellappan
 
German introduction to sp framework
German   introduction to sp frameworkGerman   introduction to sp framework
German introduction to sp frameworkBob German
 
Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web MahmoudOHassouna
 
Hnd201 Building Ibm Lotus Domino Applications With Ajax Plugins
Hnd201 Building Ibm Lotus Domino Applications With Ajax PluginsHnd201 Building Ibm Lotus Domino Applications With Ajax Plugins
Hnd201 Building Ibm Lotus Domino Applications With Ajax Pluginsdominion
 
How to build and deploy app on Replit
How to build and deploy app on ReplitHow to build and deploy app on Replit
How to build and deploy app on Replitmatiasfund
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdfBOSC Tech Labs
 
Pos 409 pos409 pos 409 forecasting and strategic planning -uopstudy.com
Pos 409 pos409 pos 409 forecasting and strategic planning -uopstudy.comPos 409 pos409 pos 409 forecasting and strategic planning -uopstudy.com
Pos 409 pos409 pos 409 forecasting and strategic planning -uopstudy.comULLPTT
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan
 
MS Day EPITA 2010: Visual Studio 2010 et Framework .NET 4.0
MS Day EPITA 2010: Visual Studio 2010 et Framework .NET 4.0MS Day EPITA 2010: Visual Studio 2010 et Framework .NET 4.0
MS Day EPITA 2010: Visual Studio 2010 et Framework .NET 4.0Thomas Conté
 
Part 3 web development
Part 3 web developmentPart 3 web development
Part 3 web developmenttechbed
 
Prg 218 entire course
Prg 218 entire coursePrg 218 entire course
Prg 218 entire coursegrades4u
 
Microsoft .NET 6 -What's All About The New Update
Microsoft .NET 6 -What's All About The New UpdateMicrosoft .NET 6 -What's All About The New Update
Microsoft .NET 6 -What's All About The New UpdateAdam John
 
Membangun Desktop App
Membangun Desktop AppMembangun Desktop App
Membangun Desktop AppFajar Baskoro
 
White Paper : ASP.NET Core AngularJs 2 and Prime
White Paper : ASP.NET Core AngularJs 2 and PrimeWhite Paper : ASP.NET Core AngularJs 2 and Prime
White Paper : ASP.NET Core AngularJs 2 and PrimeHamida Rebai Trabelsi
 
Rutgers - FrontPage 98 (Advanced)
Rutgers - FrontPage 98 (Advanced)Rutgers - FrontPage 98 (Advanced)
Rutgers - FrontPage 98 (Advanced)Michael Dobe, Ph.D.
 
Module 4: Introduction to ASP.NET 3.5 (Material)
Module 4: Introduction to ASP.NET 3.5 (Material)Module 4: Introduction to ASP.NET 3.5 (Material)
Module 4: Introduction to ASP.NET 3.5 (Material)Mohamed Saleh
 
Updated Resume
Updated ResumeUpdated Resume
Updated Resumechaunhi
 

Similaire à C# with Renas (20)

M365 global developer bootcamp 2019 PA
M365 global developer bootcamp 2019  PAM365 global developer bootcamp 2019  PA
M365 global developer bootcamp 2019 PA
 
Software Developer’s Project Documentation Template
Software Developer’s Project Documentation TemplateSoftware Developer’s Project Documentation Template
Software Developer’s Project Documentation Template
 
Basic iOS Training with SWIFT - Part 4
Basic iOS Training with SWIFT - Part 4Basic iOS Training with SWIFT - Part 4
Basic iOS Training with SWIFT - Part 4
 
German introduction to sp framework
German   introduction to sp frameworkGerman   introduction to sp framework
German introduction to sp framework
 
Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web
 
Hnd201 Building Ibm Lotus Domino Applications With Ajax Plugins
Hnd201 Building Ibm Lotus Domino Applications With Ajax PluginsHnd201 Building Ibm Lotus Domino Applications With Ajax Plugins
Hnd201 Building Ibm Lotus Domino Applications With Ajax Plugins
 
How to build and deploy app on Replit
How to build and deploy app on ReplitHow to build and deploy app on Replit
How to build and deploy app on Replit
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
 
Pos 409 pos409 pos 409 forecasting and strategic planning -uopstudy.com
Pos 409 pos409 pos 409 forecasting and strategic planning -uopstudy.comPos 409 pos409 pos 409 forecasting and strategic planning -uopstudy.com
Pos 409 pos409 pos 409 forecasting and strategic planning -uopstudy.com
 
Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2Daniel Egan Msdn Tech Days Oc Day2
Daniel Egan Msdn Tech Days Oc Day2
 
MS Day EPITA 2010: Visual Studio 2010 et Framework .NET 4.0
MS Day EPITA 2010: Visual Studio 2010 et Framework .NET 4.0MS Day EPITA 2010: Visual Studio 2010 et Framework .NET 4.0
MS Day EPITA 2010: Visual Studio 2010 et Framework .NET 4.0
 
Part 3 web development
Part 3 web developmentPart 3 web development
Part 3 web development
 
Understanding IDEs
Understanding IDEsUnderstanding IDEs
Understanding IDEs
 
Prg 218 entire course
Prg 218 entire coursePrg 218 entire course
Prg 218 entire course
 
Microsoft .NET 6 -What's All About The New Update
Microsoft .NET 6 -What's All About The New UpdateMicrosoft .NET 6 -What's All About The New Update
Microsoft .NET 6 -What's All About The New Update
 
Membangun Desktop App
Membangun Desktop AppMembangun Desktop App
Membangun Desktop App
 
White Paper : ASP.NET Core AngularJs 2 and Prime
White Paper : ASP.NET Core AngularJs 2 and PrimeWhite Paper : ASP.NET Core AngularJs 2 and Prime
White Paper : ASP.NET Core AngularJs 2 and Prime
 
Rutgers - FrontPage 98 (Advanced)
Rutgers - FrontPage 98 (Advanced)Rutgers - FrontPage 98 (Advanced)
Rutgers - FrontPage 98 (Advanced)
 
Module 4: Introduction to ASP.NET 3.5 (Material)
Module 4: Introduction to ASP.NET 3.5 (Material)Module 4: Introduction to ASP.NET 3.5 (Material)
Module 4: Introduction to ASP.NET 3.5 (Material)
 
Updated Resume
Updated ResumeUpdated Resume
Updated Resume
 

Plus de Renas Rekany

Plus de Renas Rekany (20)

decision making
decision makingdecision making
decision making
 
Artificial Neural Network
Artificial Neural NetworkArtificial Neural Network
Artificial Neural Network
 
AI heuristic search
AI heuristic searchAI heuristic search
AI heuristic search
 
AI local search
AI local searchAI local search
AI local search
 
AI simple search strategies
AI simple search strategiesAI simple search strategies
AI simple search strategies
 
C# p9
C# p9C# p9
C# p9
 
C# p8
C# p8C# p8
C# p8
 
C# p7
C# p7C# p7
C# p7
 
C# p6
C# p6C# p6
C# p6
 
C# p5
C# p5C# p5
C# p5
 
C# p4
C# p4C# p4
C# p4
 
C# p3
C# p3C# p3
C# p3
 
C# p2
C# p2C# p2
C# p2
 
Object oriented programming inheritance
Object oriented programming inheritanceObject oriented programming inheritance
Object oriented programming inheritance
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Renas Rajab Asaad
Renas Rajab Asaad Renas Rajab Asaad
Renas Rajab Asaad
 
Renas Rajab Asaad
Renas Rajab AsaadRenas Rajab Asaad
Renas Rajab Asaad
 
Renas Rajab Asaad
Renas Rajab Asaad Renas Rajab Asaad
Renas Rajab Asaad
 
Renas Rajab Asaad
Renas Rajab Asaad Renas Rajab Asaad
Renas Rajab Asaad
 
Kurdish computer skills lec1, Renas R. Rekany
Kurdish computer skills lec1, Renas R. RekanyKurdish computer skills lec1, Renas R. Rekany
Kurdish computer skills lec1, Renas R. Rekany
 

Dernier

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 

Dernier (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 

C# with Renas

  • 1. Nawroz University Object Oriented Programming C-Sharp Programming C# provides full support for object-oriented programming including encapsulation, inheritance, and polymorphism. [2017/ 2018] Rekany Renas Rajab Rekany 2017/2018
  • 2. Renas Rajab Rekany OOP 2018 1 Object Oriented Programming History of programming languages 1- Microsoft .Net Framework .NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs primarily on Microsoft Windows. It includes a large class library known as Framework Class Library (FCL) and provides language interoperability(each language can use code written in other languages) across several programming languages. Programs written for .NET Framework execute in a software environment (as contrasted to hardware environment), known as Common Language Runtime (CLR), an application virtual machine that provides services such as security, memory management, and exception handling. FCL and CLR together constitute .NET Framework. FCL provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications. Programmers produce software by combining their own source code with .NET Framework and other libraries. .NET Framework is intended to be used by most new applications created for the Windows platform. Microsoft also produces an integrated development environment largely for .NET software called Visual Studio. 2-Different DOTNET Types of Applications There are three main types of application that can be written in C#: 1. Winforms: Windows applications have the familiar graphical user interface of Windows with controls such as buttons and list boxes for input. 2. Console: Console applications use standard command-line input and output for input and output instead of a form. 3. Web Sites.
  • 3. Renas Rajab Rekany OOP 2018 2 4- Create First Winforms application Step 1: Start Visual Studio Open the Microsoft Visual Studio 2008/2015. Step 2: Create a new project Go to File -> New Project, And then New Project Dialog Appears. In the New Project Window, Select Visual C# as Project type and Windows Forms Applications as the template. Give Name and Location to your project and finally click OK button to create our first C# project.
  • 4. Renas Rajab Rekany OOP 2018 3
  • 5. Renas Rajab Rekany OOP 2018 4 Step 3: Design the user interface. When the project is created, you will see the designer view of your interface as follows. Form Designer View In this designer view of the form (Form1.cs [Design]), you can design the user interface of the single form. To do that, we use the 'Toolbox' which contains the items that you can add to your form. Toolbox is placed on the left side of your visual studio. If it is not visible go to View -> Toolbox to show the Toolbox. Toolbox
  • 6. Renas Rajab Rekany OOP 2018 5 It contains Labels, Buttons, Check Boxes, Combo Boxes and etc. This can be used to design your interface. To add elements from the Toolbox to your form double click the item or drag the item to your form. Now add a Button Control to your form by simple dragging a Button control into the form designer view. Finally it looks like below. Now our form contains two elements. Those are form and the button control. These elements have properties such as name, text, background color, fore color, etc.... To see properties for a control, select the control and all the properties are displayed in the Properties Window which appears on the right side of your visual studio. If it is not visible, Go to View -> Properties Window. Select the button and view properties as follows. Now set the text to 'Show' for the button.
  • 7. Renas Rajab Rekany OOP 2018 6 Step 4: Writing the code Double click on buttun1 to write the code private void button1_Click(object sender, EventArgs e) { MessageBox.Show("Hello World!"); } Step 5: Compile the code To compile the code Go to Build -> Build HelloWorld Step 6: Running the application To run/execute the program press F5.
  • 8. Renas Rajab Rekany OOP 2018 7 Running Application. 6- Create First Web application Building Your First Web Application Project Creating a New Project Select File->New Project within the Visual Studio 2005 IDE. This will bring up the New Project dialog. Click on the “Visual C#” node in the tree-view on the left hand side of the dialog box and choose the "ASP.NET Web Application" icon:
  • 9. Renas Rajab Rekany OOP 2018 8 Visual Studio will then create and open a new web project within the solution explorer. By default it will have a single page (Default.aspx), an AssemblyInfo.cs file, as well as a web.config file. All project file-meta-data is stored within a MSBuild based project file.
  • 10. Renas Rajab Rekany OOP 2018 9 Opening and Editing the Page Double click on the Default.aspx page in the solution explorer to open and edit the page. You can do this using either the HTML source editor or the design-view. Add a "Hello world" header to the page, along with a calendar server control and a label control (we'll use these in a later tutorial): Build and Run the Project Hit F5 to build and run the project in debug mode. By default, ASP.NET Web Application projects are configured to use the built-in VS web-server when run. The default project templates will run on a random port as a root site (for example: http://localhost:12345/):
  • 11. Renas Rajab Rekany OOP 2018 10 You can end the debug session by closing the browser window, or by choosing the Debug->Stop Debugging (Shift-F5) menu item. Customizing Project Properties ASP.NET Web Application Projects share the same configuration settings and behaviors as standard VS 2005 class library projects. You access these configuration settings by right-clicking on the project node within the Solution Explorer in VS 2005 and selecting the "Properties" context- menu item. This will then bring up the project properties configuration editor. You can use this to change the name of the generated assembly, the build compilation settings of the project, its references, its resource string values, code-signing settings, etc:
  • 12. Renas Rajab Rekany OOP 2018 11 ASP.NET Web Application Projects also add a new tab called "Web" to the project properties list. Developers use this tab to configure how a web project is run and debugged. By default, ASP.NET Web Application Projects are configured to launch and run using the built-in VS Web Server (aka Cassini) on a random HTTP port on the machine. This port number can be changed if this port is already in use, or if you want to specifically test and run using a different number:
  • 13. Renas Rajab Rekany OOP 2018 12 Alternatively, Visual Studio can connect and debug IIS when running the web application. To use IIS instead, select the "Use IIS Web Server" option and enter the url of the application to launch, connect-to, and use when F5 or Control-F5 is selected:
  • 14. Renas Rajab Rekany OOP 2018 13 Then configure the url to this application in the above property page for the web project. When you hit F5 in the project, Visual Studio will then launch a browser to that web application and automatically attach a debugger to the web-server process to enable you to debug it. Note that ASP.NET Web Application Projects can also create the IIS vroot and configure the application for you. To do this click the "Create Virtual Directory" button.
  • 15. Renas Rajab Rekany OOP 2018 14 Introduction to C# Comments 1- Single Line ( // ) Ex: int x,y,s; S=x+y; // the sum of x,y 2- Multiple Line (/* */) Ex: int x,y,s; S=x+y; /* the sum of x,y */ Arithmetic Operations Operations Arithmetic in c# Addition + Subtraction - Multiplication * Division / Modulus % Precedence of Arithmetic Operations ( ) *,/,% +,- <,<=,>,>= ==,!= = Ex z = p * r ٪ q + w / x – y (6) (1) (2) (4) (3) (5) Ex y = a * x * x + b * x + c (6) (1) (2) (4) (3) (5)
  • 16. Renas Rajab Rekany OOP 2018 15 Equality and Relational Operator Standard Operator C# Operator Ex in C# = == If (x==y) ≠ != If (x!=y) > > If (x>y) ≥ >= If (x>=y) < < If (x<y) ≤ <= If (x<=y) Assignment operations int c; c=c+3; c+=3; c ‫ــ‬ =3; c*=3; c/=3; (var) = (var) (operator) (expiration) If true (var) (operator) = (expiration) Increment and Decrement Operator Operator Call Ex ++ Pre Increment ++ a ++ Post Increment a++ -- Pre Decrement --b -- Post Decrement b-- Ex : int c=5; MessageBox.Show(c); //5 MessageBox.Show(c++); // 5 MessageBox.Show(++c); // 6 C=5; MessageBox.Show(c); // 5 MessageBox.Show(++c); // 6 MessageBox.Show(c); // 6
  • 17. Renas Rajab Rekany OOP 2018 16 Loop Statement in C# For While Do-While For (int ; condition ; increment) Ex : For (int i=0;i<=5;i++) Textbox1.text=textbox1.text+i; 0 1 2 3 4 5 While (condition) State; Ex : int i=0; While (i<=5) { Textbox1.text=textbox1.text+ i; i i =i+1; } 0 1 2 3 4 5 Do { State} While (condition); Ex : int i=0; do { Textbox1.text=textbox1.text+ i; i++; } While (i<=5); 0 1 2 3 4 5 Declarations and types 1- Goals: 1-Learn C# program structure 2-Learn what comments are. 3-Know different types of C# data types 4- Learn what Variables are. 2- General Structure of a C# Program Well, you have understand where to and how to execute your program. Each program requires three important steps to do the work. Input, Process and Output. It is the basic concept of almost all the programming language. It is also known as
  • 18. Renas Rajab Rekany OOP 2018 17 I-P-O cycle. The program requires some input from the user. Next, the program processes the input with programming language and finally shows the output. The basic structure of c# program: Using System; namespace newproject { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } } 3- Create and run a GUI (Graphic user Interface) project Step 1: Start Visual Studio Open the Microsoft Visual Studio 2008. Step 2: Create a new project Go to File -> New Project, And then New Project Dialog Appears. In the New Project Window, Select Visual C# as Project type and windows form Application as the template. Step 3: Writing the code Under the standard structure of c# program Add the following code which you will enter your name and your name will be displayed with some text message in the form.
  • 19. Renas Rajab Rekany OOP 2018 18 using System; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { textBox1.Text = "Hello Students"; } } } Step 4: Run your application Press F5 Step 5: Output: 4- Example1 Explanation: using System; It is used for including C# class library. C# has huge collection of classes and objects. If you want to use those classes then you will have to include their library name in your program. string name; //Variable for storing string value int name; // Variable for storing integer value
  • 20. Renas Rajab Rekany OOP 2018 19 . Input: For storing values into the specific variables. Eg. int a; a=5; string s; s="Hello"; Output: For getting result from the specific operations. Eg. int a; a=5; textbox1.text=Convert.Tostring(a); 5- Comments The first line contains a comment. The characters // convert the rest of the line to a comment. // A Hello World! program in C#. You can also comment out a block of text by enclosing it between the /* and */ characters. This is shown in the following example. /* A "Hello World!" program in C#. This program displays the string "Hello World!" on the screen. */ 6- C# Data Types A complete detail of C# data types are mentioned below: Data Types Size Values sbyte 8 bit -128 to 127 byte 8 bit 0 to 255
  • 21. Renas Rajab Rekany OOP 2018 20 short 16 bit -32,768 to 32,767 ushort 16 bit 0 to 65,535 int 32 bit -2,147,483,648 to 2,147,483,647 uint 32 bit 0 to 4,294,967,295 long 64 bit -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 ulong 64 bit 0 to 18,446,744,073,709,551,615 char 16 bit 0 to 65535 float 32 bit -1.5 x 1045 to 3.4 x 1038 double 64 bit -5 x 10324 to 1.7 x 10308 decimal 128 bit -1028 to 7.9 x 1028 bool --- True or false 6- Example1: Write a program in c# to find the result of adding two values. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) {
  • 22. Renas Rajab Rekany OOP 2018 21 int a, b,c; a =Convert.ToInt32( textBox1.Text); b =Convert.ToInt32( textBox2.Text); c = a + b; textBox3.Text = Convert.ToString(c); } } } OUTPIT: 7- Example2: Write a program in c# to find the result of multiplying two values. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int a, b,c; a =Convert.ToInt32( textBox1.Text);
  • 23. Renas Rajab Rekany OOP 2018 22 b =Convert.ToInt32( textBox2.Text); c = a * b; textBox3.Text = Convert.ToString(c); } }} OUTPUT: 8- Conversion C# accepts string value by default. If you are using other value then you will have to convert of specific data types. num1 = int32.Parse(Console.ReadLine()); You can use the following method to convert one data type to another data type. Integer = int32.parse() or Convert.ToInt32() int=Convert.ToInt32(string); String=Convert.ToString(integer); Double=Convert.ToDouble(); Decimal=Convert.ToDecimal(); Byte=Convert.ToByte();
  • 24. Renas Rajab Rekany OOP 2018 23 For Example: private void button1_Click(object sender, EventArgs e) { int a, b,c; a =Convert.ToInt32( textBox1.Text); b =Convert.ToInt32( textBox2.Text); c = a * b; textBox3.Text = Convert.ToString(c); } Beginning C# programming fundamentals 1- Name Spaces: The namespace keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types. 2- Conversion: You can convert a string to a number by using methods in the Convert class. Such a conversion can be useful when obtaining numerical input from a command line argument, for example. The following table lists some of the methods that you can use.
  • 25. Renas Rajab Rekany OOP 2018 24 2.1 Convert Class Numeric Type Method decimal ToDecimal(String) float ToSingle(String) double ToDouble(String) short ToInt16(String) int ToInt32(String) long ToInt64(String) Structure Conversion Method Decimal static decimal Parse(string str) Double static double Parse(string str) Single static float Parse(string str) Int64 static long Parse(string str) Int32 static int Parse(string str) Int16 static short Parse(string str) UInt64 static ulong Parse(string str) UInt32 static uint Parse(string str) UInt16 static ushort Parse(string str) Byte static byte Parse(string str) bool static bool Parse(string str) SByte static sbyte Parse(string str)
  • 26. Renas Rajab Rekany OOP 2018 25 Example1: 3- Relational Operator: In most cases, the Boolean expression, used by the if statement, uses relation operators string name; int mark; name ="Redwan" mark = Int32.Parse(85); textbox1.text=name; textbox2.text=Convert.ToString(mark);
  • 27. Renas Rajab Rekany OOP 2018 26 4- Boolean Expressions: A Boolean expression is any variable or calculation that results in a true or false condition. 5- Condition control structure Thus far, within a given function, instructions have been executed sequentially, in the same order as written. Of course that is often appropriate! On the other hands if you are planning out instructions, you can get to a place where you say, “Hm, that depends....”, and a choice must be made. The simplest choices are two-way: do one thing is a condition is true, and another (possibly nothing) if the condition is not true. 5.1The if Statement The if statement decides whether a section of code executes or not. The if statement uses a Boolean to decide whether the next statement or block of statements executes. The general C# if syntax is:
  • 28. Renas Rajab Rekany OOP 2018 27 if (expression ) {Statement(s) for if-true} Example2 : 5.2 if-else Statements The general C# if-else syntax is if (expression ) {Statement(s) for if-true} else {statement(s) for if-false} Example3: 5.3 if-else-if Statements if (expression_1) { statement; statement; etc. } Otherwise, if expression_2 is true these statements are executed, and the rest of the structure is ignored. Insert as many else if clauses as necessary. If expression_1 is true these statements are executed, and the rest of the structure is ignored. int x=2,y=4; if(x>y) MessageBox.Show("True");
  • 29. Renas Rajab Rekany OOP 2018 28 else if (expression_2) { statement; statement; etc. } else { statement; statement; etc Example4: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { These statements are executed if none of the expressions above are true. int x=2,y=4; if(x>y) MessageBox.Show("True"); else MessageBox.Show("False");
  • 30. Renas Rajab Rekany OOP 2018 29 int a, b, c; a = Convert.ToInt32(textBox2.Text); b = Convert.ToInt32(textBox3.Text); if (Convert.ToInt32(textBox1.Text) == 1) { c = a + b; textBox4.Text = Convert.ToString(c); } else if (Convert.ToInt32(textBox1.Text)==2) { c=a-b; textBox4.Text=Convert.ToString(c); } else if (Convert.ToInt32(textBox1.Text) == 3) { c = a * b; textBox4.Text = Convert.ToString(c); } else if (Convert.ToInt32(textBox1.Text) == 4) { c = a / b; textBox4.Text = Convert.ToString(c); } } } } Example5 (Switch- Condition): switch (value) { case value 1: statements break; case value 2:
  • 31. Renas Rajab Rekany OOP 2018 30 statements break; } using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int a, b, c; a = Convert.ToInt32(textBox2.Text); b = Convert.ToInt32(textBox3.Text); switch (Convert.ToInt32(textBox1.Text)) { case 1: c = a + b; textBox4.Text = Convert.ToString(c); break; case 2: c = a - b; textBox4.Text = Convert.ToString(c); break; case 3: c = a * b;
  • 32. Renas Rajab Rekany OOP 2018 31 textBox4.Text = Convert.ToString(c); break; case 4: c = a / b; textBox4.Text = Convert.ToString(c); break; } } } } OUTPUT: String Functions Definitions Clone() Make clone of string. CompareTo() Compare two strings and returns integer value as output. It returns 0 for true and 1 for false. Contains() The C# Contains method checks whether specified character or string is exists or not in the string value. EndsWith() This EndsWith Method checks whether specified character is the last character of string or not. Equals() The Equals Method in C# compares two string and returns Boolean value as output. GetHashCode() This method returns HashValue of specified string. GetType() It returns the System.Type of current instance. GetTypeCode() It returns the Stystem.TypeCode for class System.String. IndexOf() Returns the index position of first occurrence of specified
  • 33. Renas Rajab Rekany OOP 2018 32 character. ToLower() Converts String into lower case based on rules of the current culture. ToUpper() Converts String into Upper case based on rules of the current culture. Insert() Insert the string or character in the string at the specified position. IsNormalized() This method checks whether this string is in Unicode normalization form C. LastIndexOf() Returns the index position of last occurrence of specified character. Length It is a string property that returns length of string. Remove() This method deletes all the characters from beginning to specified index position. Replace() This method replaces the character. Split() This method splits the string based on specified value. StartsWith() It checks whether the first character of string is same as specified character. Substring() This method returns substring. ToCharArray() Converts string into char array. Trim() It removes extra whitespaces from beginning and ending of string. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq;
  • 34. Renas Rajab Rekany OOP 2018 33 using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string s,fn, ln; fn = textBox1.Text; ln = textBox2.Text; s = comboBox1.Text; switch (s) { case "Clone": textBox3.Text=Convert.ToString( fn.Clone()); textBox4.Text=Convert.ToString(ln.Clone()); break; case "CompareTo": int b = fn.CompareTo(ln); if (b == 0) MessageBox.Show("False"); else if (b == 1) MessageBox.Show("True"); break; case "Contains": MessageBox.Show(Convert.ToString( fn.Contains("W"))); break;
  • 35. Renas Rajab Rekany OOP 2018 34 case "EndsWith": MessageBox.Show(Convert.ToString( fn.EndsWith("d"))); break; case "Equals": MessageBox.Show(Convert.ToString( fn.Equals(ln))); break; case "GetHashCode": textBox3.Text =Convert.ToString( fn.GetHashCode()); textBox4.Text =Convert.ToString( ln.GetHashCode()); break; case "GetType": textBox3.Text = Convert.ToString(fn.GetType ()); textBox4.Text = Convert.ToString(ln.GetType ()); break; case "GetTypeCode": textBox3.Text = Convert.ToString(fn.GetTypeCode ()); textBox4.Text = Convert.ToString(ln.GetTypeCode ()); break; case "IndexOf": textBox3.Text = Convert.ToString(fn.IndexOf("e")); textBox4.Text = Convert.ToString(ln.IndexOf("o")); break; case "ToLower": textBox3.Text = Convert.ToString(fn.ToLower()); textBox4.Text = Convert.ToString(ln.ToLower()); break; case "ToUpper": textBox3.Text = Convert.ToString(fn.ToUpper()); textBox4.Text = Convert.ToString(ln.ToUpper()); break; case "Insert": textBox3.Text = Convert.ToString(fn.Insert(0, "Hi ")); textBox4.Text = Convert.ToString(ln.Insert(0, " Hi "));
  • 36. Renas Rajab Rekany OOP 2018 35 break; case "IsNormalized": MessageBox.Show(Convert.ToString(fn.IsNormalized())); break; case "LastIndexOf": textBox3.Text = Convert.ToString(fn.LastIndexOf("o")); textBox4.Text = Convert.ToString(ln.LastIndexOf("s")); break; case "Length": textBox3.Text = Convert.ToString(fn.Length); textBox4.Text = Convert.ToString(ln.Length); break; case "Remove": textBox3.Text = Convert.ToString(fn.Remove(5)); textBox4.Text = Convert.ToString(ln.Remove(0,4)); break; case "Replace": textBox3.Text = Convert.ToString(fn.Replace("o", "*")); textBox4.Text = Convert.ToString(ln.Replace("w", "*")); break; case "Split": string[] split1 = fn.Split(new char[] { 'o' }); textBox3.Text = split1[0]; string[] split2 = ln.Split(new char[] { 'd' }); textBox4.Text = split2[1]; break; case "StartsWith": textBox3.Text=Convert.ToString(fn.StartsWith("O")); textBox4.Text = Convert.ToString(ln.StartsWith("W")); break; case "SubString": textBox3.Text = Convert.ToString(fn.Substring(2, 5)); textBox4.Text = Convert.ToString(ln.Substring(4, 5));
  • 37. Renas Rajab Rekany OOP 2018 36 break; case "ToCharArray": char[] s1 = fn.ToCharArray(); char [] s2= ln.ToCharArray(); for (int i = 0; i < fn.Length; i++) { textBox3.Text = textBox3.Text + s1[i]; } for (int i = 0; i < ln.Length ; i++) { textBox4.Text = textBox4.Text + s2[i]; } break; case "Trim": textBox3.Text = Convert.ToString(fn.Trim()); textBox4.Text = Convert.ToString(ln.Trim(new char[] {'s'})); break; } } } }
  • 38. Renas Rajab Rekany OOP 2018 37 Loop control structure 1- Goals: In this chapter you will learn: • What is Loop Constructs in C#? • How many types of looping statements in C sharp? • How to use loop constructs in Programming? H.M) Write a program in C# to enter 10 degrees, then find the Grade for each of them. 2- Loop constructs The loop constructs is used to execute a block of code until the condition becomes expired. Loop constructs in C#, saves the programmer from writing code multiple times that has repetitive in nature. 2.1 For Loop:
  • 39. Renas Rajab Rekany OOP 2018 38 Example 1: OUTPUT using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string a; a = "aa"; for (int i = 0; i < 5; i++) { textBox1.Text = textBox1.Text + a; textBox1.AppendText(Environment.NewLine); } } } }
  • 40. Renas Rajab Rekany OOP 2018 39 Example 2: OUTPUT using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int i,j; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) textBox1.Text = textBox1.Text + i+j+" "; textBox1.AppendText(Environment.NewLine); } } } } H.W) Find the main diagonal, secondary diagonal, swap the rows to columns…
  • 41. Renas Rajab Rekany OOP 2018 40 2.2 While Loop: Example 3: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int num, r, i; num = Convert.ToInt32(textBox1.Text); i = 1; while (i <= 10) {
  • 42. Renas Rajab Rekany OOP 2018 41 r = num * i; textBox2.Text = textBox2.Text + r + "=" + num + "*" + i; textBox2.AppendText(Environment.NewLine); i += 1; } } } } 2.3 Do-While Loop: Note: must put semi-colon(;) at the end of while condition in do-while loop. Example 4: private void button1_Click(object sender, EventArgs e) { int num, r, i; num = Convert.ToInt32(textBox1.Text); i = 1; do { r = num * i; textBox2.Text = textBox2.Text + r + "=" + num + "*" + i; textBox2.AppendText(Environment.NewLine); i += 1; } while (i <= 10); } Q) What's the different between the (While and Do_While loop)?
  • 43. Renas Rajab Rekany OOP 2018 42 Break: The break is use in for, while, do-while, switch case. Break statement is used to terminating the current flow of program and transfer controls to the next execution. Continue: The continue is use in for, while, do-while. The continue statements enables you to skip the loop and jump the loop to next iteration. continue break for (int i=0;i<=5;i++) { if(i<=3) continue ; textBox1.Text = textBox1.Text + i; textBox1.AppendText(Environment.NewLine); } 4 5 for (int j = 0; j <= 5; j++) { if (j >= 3) break ; textBox2.Text = textBox2.Text + j; textBox2.AppendText(Environment.NewLine); } 0 1 2 EX: Break for (int i=1; i<=7;i++) { If (i==5) Break; Textbox1.text=textbox1.text+ i; } Output 1 2 3 4 Continue
  • 44. Renas Rajab Rekany OOP 2018 43 For (int i=1; i<=7;i++) { if (i==5) Continue; Textbox1.text=textbox1.text+ i; } Output 1234 678910 Build_in and User_define C# Methods 1- Method (= Function) A method is a group of statements that together perform a task. It combines related code together and makes program easier. Every C# program has at least one class with a method named Main. 2- Method Types: 1. Built in: the methods that the language provides. Such as Math class provide the following methods: Abs (x) exp (x) tan (x) Cos (x) pow (x,y) log (x) Sin (x) max (x,y) Sqrt (x) Log10, max, min, round, sqrt. Example: Math.abs(x); Textbox1.text=Convert.ToString(math.abs(-10)); Math.cos(x);
  • 45. Renas Rajab Rekany OOP 2018 44 2. User defines: the methods that the user defines and call. Example: int sum (int x , int y) {int s=x+y; Return (s);} 3- Defining Methods in C# and calling techniques: When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is as follows: Following are the various elements of a method: • Access Specifier: This determines the visibility of a variable or a method from another class. • Return type: A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void. • Method name: Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class. • Parameter list: Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters. < Access Specifier> < Return Type> < Method Name> (Parameter list) { Body }
  • 46. Renas Rajab Rekany OOP 2018 45 • Method body: This contains the set of instructions needed to complete the required activity. Example: public void add() { Body } In the preceding example, the public is an access specifier, void is a return data type that return nothing and add() is a method name. There is no parameter define in add() method. If the function returns interger value, then you can define function as follow: public int add() { Body } If the function is returning string value, then you can define function as follow: public string printname() { Body } You must remember, whenever use return data type with method, must return value using return keyword from body. If you don’t want to return any value, then you can use void data type.
  • 47. Renas Rajab Rekany OOP 2018 46 Ex: Class program { public int sqr(int a) { return (a * a); } private void button1_Click(object sender, EventArgs e) { int b; b =Convert.ToInt32( textBox1.Text); textBox2.Text = Convert.ToString(sqr(b)); } } 4- Passing arguments: pass by value Pass by reference static int sqr(int x) { return ( x * x); } ---------- Output - Before call x is 5 - After call x is 5 static int sqr2(ref int x) { return x * x; } ---------- Output - Before call x is 5 - After call x is 25
  • 48. Renas Rajab Rekany OOP 2018 47 Method overload 1. C# enable several methods of same name to be defined in same class as long as these method have different sets of parameters (number of parameter , type of parameter , order of parameter ) this is called method overloaded . 2. Method overloading commonly is used to create several methods with same name that perform similar tasks, but on different data types. Ex: Static int squire (int x) { return (x*x); } Static double squire (double x) { return (x*x); } static void main ( ) { int y = 2; double z=12.1; textBox1.Text = Convert.ToString(squire(y)); textBox1.Text = Convert.ToString(squire(z)); } Output - The squire of int 2 is 4. - The squire of double 2.1 is 4.41. Note: This is called overload method.
  • 49. Renas Rajab Rekany OOP 2018 48 Arrays (declaration 1_D, 2_D, initialization) 1- Array: Sometimes, you need to declare multiple variable of same data type. It is complex and time consuming process. Just for an example, you have to declare 100 integer type of variable then what would you do? Will you declare variable as follow: int num1,num2,num3,num4,num5,num6,num7,num8.... num100; It is not a suitable way to declare multiple variable of same data type. To overcome this situation, array came alive. An array is a collection of same data type. If you have to declare 100 variable of same data type in C#, then you can declare and initialize an array as follow. int[] num = new int[100]; 2- Structure of C# array: To understand concept of array, consider the following example. What happens in memory when we declare an integer type array? int[] num = new int[6]; Num Array:
  • 50. Renas Rajab Rekany OOP 2018 49 3- Declaration and Initialization of Array: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int[] array=new int [5]; array[0] = 3; array[1] = 6; array[2] = 2; array[3] = 7; array[4] = 9; for (int i = 0; i < 5; i++) { textBox1.Text = textBox1.Text + array[i]; textBox1.AppendText(Environment.NewLine); } } } }
  • 51. Renas Rajab Rekany OOP 2018 50 4- Storing value directly in C# program: In your program, you can directly store value in array. You can store value in array by two ways. i. Inline: int[] arr =new int[5] { 3, 6, 2, 7, 9 }; ii. Index: int[] arr = new int[5] arr[0] = 3; arr[1] = 6; arr[2] = 2; arr[3] = 7; arr[4] = 9; iii. Users input: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Microsoft.VisualBasic; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
  • 52. Renas Rajab Rekany OOP 2018 51 private void button1_Click(object sender, EventArgs e) { int[] array2 = new int[10]; for (int i = 0; i < 10; i++) { array2[i] = Convert.ToInt32(Interaction.InputBox("Enter The array elements", "Input Box", "Write Here", 75, 75)); textBox1.Text = textBox1.Text + array2[i]; textBox1.AppendText(Environment.NewLine); } } } } Hint: To define InputBox, you have to Add reference from .Net-> Microsoft.Visual Basic, then write it's library.
  • 53. Renas Rajab Rekany OOP 2018 52 5- Accessing value from array: You can access array’s value by its index position. Each index position in array refers to a memory address in which your values are saved. int[] arr=new int[6]; int num1, num2; num1 = arr[1] * arr[3]; It is same as: num1 = 23 * 9; Because, arr[1] refers to the value 23 and arr[3] refers to the value 9. If you are required to access entire value of an array one after another, then you can use loop constructs to iterate through array. Example3: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Microsoft.VisualBasic; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
  • 54. Renas Rajab Rekany OOP 2018 53 private void button1_Click(object sender, EventArgs e) { int[] id = new int[3]; string[] name = new string[3]; int i, j = 0; string f; for (i = 0; i < 3; i++) { id[i] = Convert.ToInt32(Interaction.InputBox("Enter the id", "InputBox", "Enter Here", 75, 75)); name[i] = Interaction.InputBox("Enter the name", "InputBox", "Enter Here", 75, 75); } f = Interaction.InputBox("Enter the name to find", "InputBox", "Enter Here", 75, 75); for (i = 0; i < 3; i++) { if (name[i] == f) { MessageBox.Show(Convert.ToString(id[i]), "The Id is:"); j++; } } if (j == 0) MessageBox.Show("Not Found"); } } } Hint: To define InputBox, you have to Add reference from .Net-> Microsoft. Visual Basic, then write it's library.
  • 55. Renas Rajab Rekany OOP 2018 54 Array dimensions A. One dimensional: The one dimensional array or single dimensional array in C# is the simplest type of array that contains only one row for storing data. It has single set of square bracket (“[]”). To declare single dimensional array in C#, you can write the following code. Example4: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) {
  • 56. Renas Rajab Rekany OOP 2018 55 string[] books = new string[5] { "C#", "VB", "JAVA", "C++", "MATLAB" }; textBox1.Text = "First Second Third Four Five"; textBox1.AppendText(Environment.NewLine); textBox1.Text = textBox1.Text + "_______________________________"; textBox1.AppendText(Environment.NewLine); for (int i = 0; i < 5; i++) { textBox1.Text = textBox1.Text + books[i] + " "; } } } } OUTPUT: B. Multi-dimensional array: The multi-dimensional array in C# is such type of array that contains more than one row to store data on it. The multi-dimensional array is also known as rectangular array in c sharp because it has same length of each row. It can be two dimensional array or three dimensional array or more. It contains more than one coma (,) within single rectangular brackets (“[ , , ,]”). To storing and accessing the elements from
  • 57. Renas Rajab Rekany OOP 2018 56 multidimensional array, you need to use nested loop in program. The following example will help you to figure out the concept of multidimensional array. Example5: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) {
  • 58. Renas Rajab Rekany OOP 2018 57 string[,] books = new string[3,3]{ { "C#", "VB", "JAVA"},{".NET", "C++", "DB" },{"SQL","HTML","XML"}}; textBox1.Text = "First Second Third "; textBox1.AppendText(Environment.NewLine); textBox1.Text = textBox1.Text + "___________________________"; textBox1.AppendText(Environment.NewLine); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { textBox1.Text = textBox1.Text + books[i, j] + " "; } textBox1.AppendText(Environment.NewLine); } } } } OUTPUT:
  • 59. Renas Rajab Rekany OOP 2018 58 Passing array An array can also be passed to method as argument or parameter. A method process the array and returns output. Passing array as parameter in C# is pretty easy as passing other value as parameter. Just create a function that accepts array as argument and then process them. The following demonstration will help you to understand how to pass array as argument in C# programming. Example4: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void printarray(int[] print) { int i; for (i = 0; i < 5; i++) { textBox1.Text = textBox1.Text + print[i]; textBox1.AppendText(Environment.NewLine); } } private void button1_Click(object sender, EventArgs e) { int[] num = new int[5] { 2, 4, 6, 8, 10 }; printarray(num); } } }
  • 60. Renas Rajab Rekany OOP 2018 59 Most common properties of Array class Properties Explanation Example Length Returns the length of array. Returns integer value. int i = arr1.Length; Rank Returns total number of items in all the dimension. Returns integer value. int i = arr1.Rank; IsFixedSize Check whether array is fixed size or not. Returns Boolean value bool i = arr.IsFixedSize; IsReadOnly Check whether array is ReadOnly or not. Returns Boolean value bool k = arr1.IsReadOnly; H.M) Apply these properties in arrays (Max, Min, Sum, Average, First, Last). Most common functions of Array class Function Explanation Example Sort Sort an array Array.Sort(arr); Clear Clear an array by removing all the items Array.Clear(arr, 0, 3); GetLength Returns the number of elements arr.GetLength(0); GetValue Returns the value of specified items arr.GetValue(2); IndexOf Returns the index position of value Array.IndexOf(arr,45); Copy Copy array elements to another elements Array.Copy(arr1,arr1,3); Example5: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text;
  • 61. Renas Rajab Rekany OOP 2018 60 using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void arr_mul(int[] array1) { int i; double mul = 1; for (i = 0; i < 5; i++) { textBox8.Text = textBox8.Text + array1[i]; mul *= array1[i]; } for (i = 0; i < 5; i++) { textBox9.Text = textBox9.Text+array1[i].ToString(); } Array.Sort(array1); for(i=0;i<5;i++) { textBox6.Text = textBox6.Text + array1[i].ToString(); } textBox11.Text = mul.ToString() ; } private void button1_Click(object sender, EventArgs e) { int[] arr1 = new int[5] { 7, 3, 12, 8, 11 }; int[] arr2 = new int[5]; int len, r,gl,gt; bool fixedsize, read_only; Array.Copy(arr1, arr2, arr1.Length); len = arr1.Length; textBox1.Text = len.ToString(); r=arr1.Rank; textBox2.Text = r.ToString();
  • 62. Renas Rajab Rekany OOP 2018 61 fixedsize = arr1.IsFixedSize; textBox3.Text = fixedsize.ToString(); read_only = arr1.IsReadOnly; textBox4.Text = read_only.ToString(); gl=arr1.GetLength(0); textBox5.Text = gl.ToString(); textBox10.Text = arr1.Sum().ToString(); gt=Convert.ToInt32(textBox7.Text); textBox8.Text = arr1.GetValue(gt).ToString(); arr_mul(arr1); } } } Q) Write a program in C# to find the following in array, (Copy, Reverse, Find, Resize).
  • 63. Renas Rajab Rekany OOP 2018 62 Events TextBox lets users type letters and enter data. It is part of the Windows Forms platform and is used with C# code. It is added with the Visual Studio designer. Many events and properties are available on this control. Intro. First, the TextBox will take care of reading the keys and displaying the text. But it will not do anything with the text it accepts. You will need to access the text from the TextBox based on custom logic rules. Events. In Visual Studio the lightning bolt symbol describes event handlers. Windows Forms programs are primarily event-based, which means you can use the lightning bolt icon in the Properties dialog to add the most important event handlers.
  • 64. Renas Rajab Rekany OOP 2018 63 TextChanged. You can use the TextChanged event to modify another part of your program when the user types text into a TextBox. The TextChanged event is only triggered when the text is changed to something different, not changed to the same value. This program assigns the base window's title text to the text typed in by the user to the TextBox. This makes the base window's title reflect the user's input. The Windows taskbar will also show this text. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void textBox1_TextChanged(object sender, EventArgs e) { // // This changes the main window text when you type into the TextBox. // this.Text = textBox1.Text; } } }
  • 65. Renas Rajab Rekany OOP 2018 64 KeyDown. You can read key down events in the TextBox control in Windows Forms. The Windows Forms system provides several key-based events. This tutorial uses the KeyDown event handler which is called before the key value actually is painted. You can cancel the key event in the KeyDown event handler as well, although this is not demonstrated. The program will display an alert when the Enter key is pressed. An alternative alert message when the Escape key is pressed. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void textBox1_KeyDown(object sender, KeyEventArgs e) { // // Detect the KeyEventArg's key enumerated constant. // if (e.KeyCode == Keys.Enter) { MessageBox.Show("You pressed enter! Good job!"); } else if (e.KeyCode == Keys.Escape) { MessageBox.Show("You pressed escape! What's wrong?"); } } } }
  • 66. Renas Rajab Rekany OOP 2018 65 Multiline. You can use the Multiline property on the TextBox control to create a longer text input area. The TextBox control has performance problems with large amounts of text. But for shorter multiline input boxes, this is useful. Using TextBox with button. The screenshot shows a TextBox that was modified in the designer to have its multiline property set to true. The form also has a Button control with the text "Save" on it. Files. You can make the TextBox control do something that could be useful in a real program: write the file to disk. This is essentially a primitive word processor. But don't use it to write anything important yet. After adding the multiline TextBox, we can add a Button and add the button1_Click event handler. In that event handler, we can access the TextBox Text property and write it to a location on the hard disk.
  • 67. Renas Rajab Rekany OOP 2018 66 using System; using System.IO; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // // This is the button labeled "Save" in the program. // File.WriteAllText("C:demo.txt", textBox1.Text); } } } Result This is some text written for the textbox tutorial The example calls the File.WriteAllText method. This method will take the string data pointed to by the string reference returned by the Text property. It then actually writes that to the physical hard disk on the computer. TextBox.AppendText. TextBox provides the AppendText method. This method appends lines of text to a TextBox control. With it we have to deal with newlines and avoid extra line breaks. We are using the TextBox in multiline mode. Example. We can append text to a TextBox with the method AppendText. However, that will not append a newline or line feed to the end of the text, so when you call textBox1.AppendText("text") two times, the text will be on the same line. private void Test() { for (int i = 0; i < 2; i++) { textBox1.AppendText("Some text"); } }
  • 68. Renas Rajab Rekany OOP 2018 67 Example 2. You can append lines by using Environment.NewLine and then adding some conditional logic to determine the first and last lines. This is better than any version of AppendLine or AppendText. It doesn't add extra newlines. public partial class Form1 : Form { private void AppendTextBoxLine(string myStr) { if (textBox1.Text.Length > 0) { textBox1.AppendText(Environment.NewLine); } textBox1.AppendText(myStr); } private void TestMethod() { for (int i = 0; i < 2; i++) { AppendTextBoxLine("Some text"); } } } Contents of TextBox Some text Some text Example 3. If you don't check the length of the Text in the TextBox, you will have unwanted line breaks in your TextBox. However, for less important code, you may prefer the slightly simpler method. The following code always appends newlines. public partial class Browser : Form { private void Test() { // Will leave a blank line on the end. for (int i = 0; i < 2; i++) { textBox1.AppendText("Some text" + Environment.NewLine); } // Will leave a blank line on the start. for (int i = 0; i < 2; i++) { textBox1.AppendText(Environment.NewLine + "Some text"); } } }
  • 69. Renas Rajab Rekany OOP 2018 68 ListBox stores several text items. It can interact with other controls, including Button controls. We use this control in Windows Forms. In the example program it interacts with two Buttons—through the Button Click event handler. Tutorial. First, create a new Windows Forms C# project, and then open the Toolbox and double-click on the ListBox item. This will insert a new ListBox into your Windows Forms designer. If you want to use Buttons with the ListBox, add those too. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication11 { public partial class Form1 : Form { List<string> _items = new List<string>(); // <-- Add this public Form1() { InitializeComponent(); _items.Add("One"); // <-- Add these _items.Add("Two"); _items.Add("Three"); listBox1.DataSource = _items; } } }
  • 70. Renas Rajab Rekany OOP 2018 69 In this example, we see a List of strings at the class level. This is a good place to store the lines you want to show in your ListBox. In the constructor, we add three elements to the List. DataSource:At the final point in the constructor, we assign the DataSource from the listBox1 to the new List. Button. Go back to your Designer window in Visual Studio where you see the image of the Form. Select the buttons and then add the text "Add" and "Remove" to their Text properties in the Properties pane. Add event handlers. Here we double-click on each button in the Designer. You will be taken to the C# code view and a new event handler will have been inserted. In these event handlers, we manipulate the List and refresh the ListBox. private void button1_Click(object sender, EventArgs e) { // The Add button was clicked. _items.Add("New item " + DateTime.Now.Second); // <-- Any string you want // Change the DataSource. listBox1.DataSource = null; listBox1.DataSource = _items; } private void button2_Click(object sender, EventArgs e) { // The Remove button was clicked. int selectedIndex = listBox1.SelectedIndex; try { // Remove the item in the List. _items.RemoveAt(selectedIndex); } catch { } listBox1.DataSource = null; listBox1.DataSource = _items; }
  • 71. Renas Rajab Rekany OOP 2018 70 Form. Here we see the complete code for the Form.cs file, which acts on the ListBox and two Buttons in the Designer. It shows how to add and remove items to the ListBox with the buttons. using System; using System.Collections.Generic; using System.Windows.Forms; namespace WindowsFormsApplication11 { public partial class Form1 : Form { List<string> _items = new List<string>(); public Form1() { InitializeComponent(); _items.Add("One"); _items.Add("Two"); _items.Add("Three"); listBox1.DataSource = _items; } private void button1_Click(object sender, EventArgs e) { // The Add button was clicked. _items.Add("New item " + DateTime.Now.Second); // Change the DataSource. listBox1.DataSource = null; listBox1.DataSource = _items; } private void button2_Click(object sender, EventArgs e) { // The Remove button was clicked. int selectedIndex = listBox1.SelectedIndex; try { // Remove the item in the List. _items.RemoveAt(selectedIndex); } catch { } listBox1.DataSource = null;
  • 72. Renas Rajab Rekany OOP 2018 71 listBox1.DataSource = _items; } } } Enabled. You can easily change the Enabled state of your Add and Remove buttons by setting the Enabled property equal to false or true when the List is full or empty. This example demonstrates setting Enabled. private void button1_Click(object sender, EventArgs e) { // The Add button was clicked. // ... button2.Enabled = true; } private void button2_Click(object sender, EventArgs e) { // The Remove button was clicked. // .... if (listBox1.Items.Count == 0) { button2.Enabled = false; } } In this example, there are two button click event handlers. Button1 is the Add button, so it always sets the Enabled property of Add to true. Button2 is the Remove button, so it is disabled when there are no items in the ListBox. ComboBox is a combination TextBox with a drop-down. Its drop-down list presents preset choices. The user can type anything into the ComboBox. Alternatively, he or she can select something from the list. Example. To begin, please create a new Windows Forms application and add a ComboBox to it. You can then right-click on the ComboBox and add the SelectedIndexChanged and TextChanged event handlers in the Properties dialog. This program shows how when you change the text by typing in the ComboBox or by
  • 73. Renas Rajab Rekany OOP 2018 72 clicking on the list of Items, the event handlers are triggered. Please see the section on the Items property before running the program. using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } int _selectedIndex; string _text; private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { // Called when a new index is selected. _selectedIndex = comboBox1.SelectedIndex; Display(); } private void comboBox1_TextChanged(object sender, EventArgs e) { // Called whenever text changes. _text = comboBox1.Text; Display(); } void Display() { this.Text = string.Format("Text: {0}; SelectedIndex: {1}",_text,_selectedIndex); } } } Text. The Text property of the ComboBox functions much like the Text property of a TextBox. If you assign to the Text property, the current value in the ComboBox will change. You can also read the Text property and assign string variables to it. Items. The Items property contains the strings that are found in the drop-down part of the ComboBox. You can type the Items line-by-line into Visual Studio through the Items dialog, or you can dynamically add them during runtime. To add Items, call the Add method: use the syntax comboBox1.Add("Value"). You can also Clear the ComboBox with Clear().
  • 74. Renas Rajab Rekany OOP 2018 73 RadioButton allows distinct selection of several items. In each group of RadioButtons, only one can be checked or selected. Conceptually, this control implements an exclusive selection. CheckBoxes allow multiple selections at once. Steps. To begin, you should make a new Windows Forms application in Visual Studio, and then you can add GroupBox (or Panel) controls to it. In these controls, you can nest RadioButton instances. By using this nesting strategy , you can have multiple groups of RadioButtons on a single form. You may want to add the CheckedChanged event handler on your RadioButtons. You can actually have all the RadioButtons point to the same CheckedChanged event handler using the event window in Visual Studio. using System; using System.Windows.Forms; namespace WindowsFormsApplication11 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void radioButton1_CheckedChanged(object sender, EventArgs e) { // Executed when any radio button is changed. // ... It is wired up to every single radio button. // Search for first radio button in GroupBox. string result1 = null; foreach (Control control in this.groupBox1.Controls) { if (control is RadioButton)
  • 75. Renas Rajab Rekany OOP 2018 74 { RadioButton radio = control as RadioButton; if (radio.Checked) { result1 = radio.Text; } } } // Search second GroupBox. string result2 = null; foreach (Control control in this.groupBox2.Controls) { if (control is RadioButton) { RadioButton radio = control as RadioButton; if (radio.Checked) { result2 = radio.Text; } } } this.Text = result1 + " " + result2; } } } In the example, we wired up all six RadioButtons to the radioButton1_CheckedChanged event handler. Thus, whenever the user clicks or changes the selection on the form, the above method will be executed. ErrorProvider simplifies and streamlines error presentation. It is an abstraction that shows errors on your form. It does not require a lot of work on your part. This is its key feature. Start. To start, please open the Toolbox pane in Visual Studio. Find and double-click on the ErrorProvider icon. This will insert the errorprovider1 into the tray at the bottom of the screen. You can change properties on the ErrorProvider instance by right-clicking on it and selecting Properties.
  • 76. Renas Rajab Rekany OOP 2018 75 Example. We start with the basics. We must activate the ErrorProvider in our Windows Forms program. The ErrorProvider won't initiate any actions. It will be invoked through other event handlers in the program. In the example, we have a TextBox control and a TextChanged event handler on that control. When the TextChanged event handler is triggered, we check to see if a digit character is present. If one is not, we activate an error through the ErrorProvider. Otherwise we clear the ErrorProvider. using System; using System.Windows.Forms; namespace WindowsFormsApplication8 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void textBox1_TextChanged(object sender, EventArgs e) { // Determine if the TextBox has a digit character. string text = textBox1.Text; bool hasDigit = false; foreach (char letter in text) { if (char.IsDigit(letter)) { hasDigit = true; break; } } // Call SetError or Clear on the ErrorProvider. if (!hasDigit) { errorProvider1.SetError(textBox1, "Needs to contain a digit"); } else { errorProvider1.Clear(); } } } }
  • 77. Renas Rajab Rekany OOP 2018 76 Using SetError method. The first argument of SetError is the identifier of the TextBox control. The second argument is the error message itself. The first argument tells the ErrorProvider where to draw the error sign. Using Clear method. It is also important that you use the Clear method when appropriate. If a digit was located, we simply remove the error sign from the user interface. This instantly tells our user that no error is still present. StatusStrip. A StatusStrip displays window status. It is usually at the bottom of a window. We use a ToolStripStatusLabel hyperlink in the C# Windows Forms status bar. Intro. We see an example of StatusStrip in Windows Forms, with tips on how to use its properties. We introduce some parts of the Windows Forms program. Some notes. There are other controls such as LinkLabel that you can use for links. But this article is about my favorite way, the hyperlink in the status bar. StatusStrip. The StatusStrip is a control in your Toolbox in Visual Studio. Double click on its icon and then it will appear in the tray at the bottom of the Visual Studio window. Items:Select the status strip control on your form, and in the Properties pane look through the entries there and select Items. Labels:In the Items window you can add things to the StatusStrip. Add new ToolStripStatusLabels and a hyperlink. Steps. I will assume you already have a StatusStrip. There are a few important things. All of the items will be squished to the left of the status strip by default. We can change this, and right-align a label. Here are the steps required to configure the StatusStrip. Spring:To right-align things on a StatusStrip we add a "spring" in between the left and right items. First step. Please open the Items dialog in Visual Studio. On your StatusStrip, open the Items Collection Editor dialog in the A-Z listing. Second, add some items. Leave the Status Label dropdown selected and click on the big Add button. You can also add other types of controls to your status strip here. To add a hyperlink, you can use a regular status label. You can make it a hyperlink later. Third, add a ToolStripStatusLabel with "Spring" set to true. Put it after the leftmost (first) status item. Add another status label after it. This will right-align the third status label. On the right side of the Items Collection Editor dialog, you will see another grid list. Scroll to Text and type in the text of your link. Set the IsLink property to true. Hyperlink. Double-click on the ToolStripStatusLabel you want to turn into a hyperlink. We must use the Click event handler to make the status item do something when it is clicked.
  • 78. Renas Rajab Rekany OOP 2018 77 Process:To start a web browser, we will need to use the Process.Start method in System.Diagnostics. In the new Click event handler, add the inner line here. You can directly access System.Diagnostics. private void toolStripStatusLabel_Click(object sender,EventArgs e) { // Launch any website. // ... You should change the URL! System.Diagnostics.Process.Start("http://www.any.com/"); } Background Color and Foreground Color You can set background color and foreground color through property window and programmatically. textBox1.BackColor = Color.Blue; textBox1.ForeColor = Color.White; Textbox BorderStyle You can set 3 different types of border style for textbox, they are None, FixedSingle and fixed3d. textBox1.BorderStyle = BorderStyle.Fixed3D; TextBox Events Keydown event You can capture which key is pressed by the user using KeyDown event
  • 79. Renas Rajab Rekany OOP 2018 78 TextChanged Event When user input or setting the Text property to a new value raises the TextChanged event Textbox Maximum Length Sets the maximum number of characters or words the user can input into the text box control. textBox1.MaxLength = 40; Textbox ReadOnly When a program wants to prevent a user from changing the text that appears in a text box, the program can set the controls Read-only property is to True. textBox1.ReadOnly = true; Multiline TextBox You can use the Multiline and ScrollBars properties to enable multiple lines of text to be displayed or entered. textBox1.Multiline = true; Textbox passowrd character TextBox controls can also be used to accept passwords and other sensitive information. You can use the PasswordChar property to mask characters entered in a single line version of the control textBox1.PasswordChar = '*'; The above code set the PasswordChar to * , so when the user enter password then it display only * instead of typed characters.
  • 80. Renas Rajab Rekany OOP 2018 79 How to Newline in a TextBox You can add new line in a textbox using many ways. textBox1.Text += "your text" + "rn"; or textBox1.Text += "your text" + Environment.NewLine; using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { textBox1.Width = 250; textBox1.Height = 50; textBox1.Multiline = true; textBox1.BackColor = Color.Blue; textBox1.ForeColor = Color.White; textBox1.BorderStyle = BorderStyle.Fixed3D; } private void button1_Click(object sender, EventArgs e) { string var; var = textBox1.Text; MessageBox.Show(var); } } } You can use Regular Expression to validate a Textbox to enter number only. System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[ ^ 0-9]")
  • 81. Renas Rajab Rekany OOP 2018 80 The following method also you can force your user to enter numeric value only. if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; } If you want to allow decimals add the following to the above code. if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void textBox1_TextChanged(object sender, EventArgs e) { if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, " ^ [0-9]")) { textBox1.Text = ""; } } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } } } }
  • 82. Renas Rajab Rekany OOP 2018 81 C# ProgressBar Control A progress bar is a control that an application can use to indicate the progress of a lengthy operation such as calculating a complex result, downloading a large file from the Web etc. ProgressBar controls are used whenever an operation takes more than a short period of time. The Maximum and Minimum properties define the range of values to represent the progress of a task. Minimum : Sets the lower value for the range of valid values for progress. Maximum : Sets the upper value for the range of valid values for progress. Value : This property obtains or sets the current level of progress. By default, Minimum and Maximum are set to 0 and 100. As the task proceeds, the ProgressBar fills in from the left to the right. To delay the program briefly so that you can view changes in the progress bar clearly. The following C# program shows a simple operation in a progressbar. using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int i; progressBar1.Minimum = 0; progressBar1.Maximum = 200; for (i = 0; i <= 200; i++)
  • 83. Renas Rajab Rekany OOP 2018 82 { progressBar1.Value = i; } } } } C# DateTimePicker Control The DateTimePicker control allows you to display and collect date and time from the user with a specified format. The DateTimePicker control has two parts, a label that displays the selected date and a popup calendar that allows users to select a new date. The most important property of the DateTimePicker is the Value property, which holds the selected date and time. dateTimePicker1.Value = DateTime.Today; The Value property contains the current date and time the control is set to. You can use the Text property or the appropriate member of Value to get the date and time value. DateTime iDate; iDate = dateTimePicker1.Value;
  • 84. Renas Rajab Rekany OOP 2018 83 The control can display one of several styles, depending on its property values. The values can be displayed in four formats, which are set by the Format property: Long, Short, Time, or Custom. dateTimePicker1.Format = DateTimePickerFormat.Short; using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { dateTimePicker1.Format = DateTimePickerFormat.Short; dateTimePicker1.Value = DateTime.Today; } private void button1_Click(object sender, EventArgs e) { DateTime iDate; iDate = dateTimePicker1.Value; MessageBox.Show("Selected date is " + iDate); } } } C# Menu Control A Menu on a Windows Form is created with a MainMenu object, which is a collection of MenuItem objects. MainMenu is the container for the Menu structure of the form and menus are made of MenuItem objects that represent individual parts of a menu. You can add menus to Windows Forms at design time by adding the MainMenu component and then appending menu items to it using the Menu Designer.
  • 85. Renas Rajab Rekany OOP 2018 84 After drag the Menustrip on your form you can directly create the menu items by type a value into the "Type Here" box on the menubar part of your form. If you need a seperator bar , right click on your menu then go to insert->Seperator.
  • 86. Renas Rajab Rekany OOP 2018 85 After creating the Menu on the form , you have to double click on each menu item and write the programs there depends on your requirements. The following C# program shows how to show a messagebox when clicking a Menu item. using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void menu1ToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("You are selected MenuItem_1"); } } } C# Color Dialog Box There are several classes that implement common dialog boxes, such as color selection , print setup etc. A ColorDialog object is a dialog box with a list of colors that are defined for the display system. The user can select or create a particular color from the list, which is then
  • 87. Renas Rajab Rekany OOP 2018 86 reported back to the application when the dialog box exits. You can invite a color dialog box by calling ShowDialog() method. ColorDialog dlg = new ColorDialog(); dlg.ShowDialog(); The following C# program invites a color dialog box and retrieve the selected color to a string. using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { ColorDialog dlg = new ColorDialog(); dlg.ShowDialog(); if (dlg.ShowDialog() == DialogResult.OK) { string str = null; str = dlg.Color.Name; MessageBox.Show (str); } } } } C# Font Dialog Box Font dialog box represents a common dialog box that displays a list of fonts that are currently installed on the system. The Font dialog box lets the user choose attributes for a logical font, such as font family and associated font style, point size, effects , and a script.
  • 88. Renas Rajab Rekany OOP 2018 87 using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { FontDialog dlg = new FontDialog(); dlg.ShowDialog(); if (dlg.ShowDialog() == DialogResult.OK) { string fontName; float fontSize; fontName = dlg.Font.Name; fontSize = dlg.Font.Size; MessageBox.Show(fontName + " " + fontSize ); } } } }
  • 89. Renas Rajab Rekany OOP 2018 88 C# OpenFile Dialog Box The OpenFileDialog component allows users to browse the folders of their computer or any computer on the network and select one or more files to open. The dialog box returns the path and name of the file the user selected in the dialog box. The FileName property can be set prior to showing the dialog box. This causes the dialog box to initially display the given filename. In most cases, your applications should set the InitialDirectory, Filter, and FilterIndex properties prior to calling ShowDialog. The following C# program invites an OpenFile Dialog Box and retrieve the selected filename to a string. using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.ShowDialog(); if (dlg.ShowDialog() == DialogResult.OK)
  • 90. Renas Rajab Rekany OOP 2018 89 { string fileName; fileName = dlg.FileName; MessageBox.Show(fileName); } } } } C# Print Dialog Box A user can use the Print dialog box to select a printer, configure it, and perform a print job. Print dialog boxes provide an easy way to implement Print and Print Setup dialog boxes in a manner consistent with Windows standards. The Print dialog box includes a Print Range group of radio buttons that indicate whether the user wants to print all pages, a range of pages, or only the selected text. The dialog box includes an edit control in which the user can type the number of copies to print. By default, the Print dialog box initially displays information about the current default printer. using System; using System.Drawing; using System.Windows.Forms; namespace Win dowsFormsApplication1 { public partial class Form1 : Form { public Form1() {
  • 91. Renas Rajab Rekany OOP 2018 90 InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { PrintDialog dlg = new PrintDialog(); dlg.ShowDialog(); } } } C# Label Control Labels are one of the most frequently used C# control. We can use the Label control to display text in a set location on the page. Label controls can also be used to add descriptive text to a Form to provide the user with helpful information. The Label class is defined in the System.Windows.Forms namespace. Add a Label control to the form - Click Label in the Toolbox and drag it over the forms Designer and drop it in the desired location. If you want to change the display text of the Label, you have to set a new text to the Text property of Label. label1.Text = "This is my first Label"; In addition to displaying text, the Label control can also display an image using the Image property, or a combination of the ImageIndex and ImageList properties. label1.Image = Image.FromFile("C:testimage.jpg"); using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
  • 92. Renas Rajab Rekany OOP 2018 91 private void Form1_Load(object sender, EventArgs e) { label1.Text = "This is my first Lable"; label1.BorderStyle = BorderStyle.FixedSingle; label1.TextAlign = ContentAlignment.MiddleCenter; } } } C# Button Control Windows Forms controls are reusable components that encapsulate user interface functionality and are used in client side Windows applications. A button is a control, which is an interactive component that enables users to communicate with an application. The Button class inherits directly from the ButtonBase class. A Button can be clicked by using the mouse, ENTER key, or SPACEBAR if the button has focus. When you want to change display text of the Button , you can change the Text property of the button. button1.Text = "Click Here"; Similarly if you want to load an Image to a Button control , you can code like this button1.Image = Image.FromFile("C:testimage.jpg"); How to Call a Button's Click Event Programmatically The Click event is raised when the Button control is clicked. This event is commonly used when no command name is associated with the Button control. Raising an event invokes the event handler through a delegate. private void Form1_Load(object sender, EventArgs e) { Button b = new Button(); b.Click += new EventHandler(ShowMessage); Controls.Add(b); } private void ShowMessage(object sender, EventArgs e) { MessageBox.Show("Button Click"); }
  • 93. Renas Rajab Rekany OOP 2018 92 C# MDI Form A Multiple Document Interface (MDI) programs can display multiple child windows inside them. This is in contrast to single document interface (SDI) applications, which can manipulate only one document at a time. Visual Studio Environment is an example of Multiple Document Interface (MDI) and notepad is an example of an SDI application. MDI applications often have a Window menu item with submenus for switching between windows or documents. Any windows can become an MDI parent, if you set the IsMdiContainer property to True. IsMdiContainer = true; The following C# program shows a MDI form with two child forms. Create a new C# project, then you will get a default form Form1 . Then add two mnore forms in the project (Form2 , Form 3) . Create a Menu on your form and call these two forms on menu click event. NOTE: If you want the MDI parent to auto-size the child form you can code like this.
  • 94. Renas Rajab Rekany OOP 2018 93 form.MdiParent = this; form.Dock=DockStyle.Fill; form.Show(); using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { IsMdiContainer = true; } private void menu1ToolStripMenuItem_Click(object sender, EventArgs e) { Form2 frm2 = new Form2(); frm2.Show(); frm2.MdiParent = this; } private void menu2ToolStripMenuItem_Click(object sender, EventArgs e) { Form3 frm3 = new Form3(); frm3.Show(); frm3.MdiParent = this; } } } keyPress event in C# Handle Keyboard Input at the Form Level in C# Windows Forms processes keyboard input by raising keyboard events in response to Windows messages. Most Windows Forms applications process keyboard input exclusively by handling the keyboard events. How do I detect keys pressed in C# You can detect most physical key presses by handling the KeyDown or KeyUp events. Key events occur in the following order:
  • 95. Renas Rajab Rekany OOP 2018 94 KeyDown KeyPress KeyUp How to detect when the Enter Key Pressed in C# The following C# code behind creates the KeyDown event handler. If the key that is pressed is the Enter key, a MessegeBox will displayed . if (e.KeyCode == Keys.Enter) { MessageBox.Show("Enter Key Pressed "); } How to get TextBox1_KeyDown event in your C# source file ? Select your TextBox control on your Form and go to Properties window. Select Event icon on the properties window and scroll down and find the KeyDown event from the list and double click the Keydown Event. The you will get the KeyDown event in your source code editor. private void textBox1_KeyDown(.....) { }
  • 96. Renas Rajab Rekany OOP 2018 95 Difference between the KeyDown Event, KeyPress Event and KeyUp Event KeyDown Event : This event raised as soon as the user presses a key on the keyboard, it repeats while the user keeps the key depressed. KeyPress Event : This event is raised for character keys while the key is pressed and then released. This event is not raised by noncharacter keys, unlike KeyDown and KeyUp, which are also raised for noncharacter keys KeyUp Event : This event is raised after the user releases a key on the keyboard. KeyPress Event : using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Enter) { MessageBox.Show("Enter key pressed"); } if (e.KeyChar == 13) { MessageBox.Show("Enter key pressed"); } } } } KeyDown Event : using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) {
  • 97. Renas Rajab Rekany OOP 2018 96 MessageBox.Show("Enter key pressed"); } } } } How to Detecting arrow keys in C# In order to capture keystrokes in a Forms control, you must derive a new class that is based on the class of the control that you want, and you override the ProcessCmdKey(). KeyUp Event : The following C# source code shows how to capture Enter KeyDown event from a TextBox Control. using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void textBox1_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { MessageBox.Show("Enter key pressed"); } } } } How to create Dynamic Controls in C# ? How to create Control Arrays in C# ? Visual Studio .NET does not have control arrays like Visual Basic 6.0 does. The good news is that you can still set things up to do similar things. The advantages of C# dynamic controls is that they can be created in response to how the user interacts with the application. Common controls that are added during run-time are the Button and TextBox controls. But of course, nearly every C# control can be created dynamically.
  • 98. Renas Rajab Rekany OOP 2018 97 How to create Dynamic Controls in C# ? The following program shows how to create a dynamic TextBox control in C# and setting the properties dynamically for each TextBox control. Drag a Button control in the form and copy and paste the following source code. using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { int cLeft = 1; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { AddNewTextBox(); } public System.Windows.Forms.TextBox AddNewTextBox() { System.Windows.Forms.TextBox txt = new System.Windows.Forms.TextBox(); this.Controls.Add(txt); txt.Top = cLeft * 25; txt.Left = 100; txt.Text = "TextBox " + this.cLeft.ToString(); cLeft = cLeft + 1; return txt; } } }
  • 99. Renas Rajab Rekany OOP 2018 98 Keep Form on Top of All Other Windows The System.Windows.Forms namespace contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system. You can bring a Form on top of application by simply setting the Form.topmost form property to true will force the form to the top layer of the screen, while leaving the user able to enter data in the forms below. Form2 frm = new Form2(); frm.TopMost = true; frm.Show(); Topmost forms are always displayed at the highest point in the z-order of the windows on the desktop. You can use this property to create a form that is always displayed in your application, such as a MessageBox window. using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 frm = new Form2(); frm.TopMost = true; frm.Show(); } } }
  • 100. Renas Rajab Rekany OOP 2018 99 C# Timer Control What is Timer Control ? The Timer Control plays an important role in the development of programs both Client side and Server side development as well as in Windows Services. With the Timer Control we can raise events at a specific interval of time without the interaction of another thread. Use of Timer Control We require Timer Object in many situations on our development environment. We have to use Timer Object when we want to set an interval between events, periodic checking, to start a process at a fixed time schedule, to increase or decrease the speed in an animation graphics with time schedule etc. A Timer control does not have a visual representation and works as a component in the background. How to Timer Control ? We can control programs with Timer Control in millisecond, seconds, minutes and even in hours. The Timer Control allows us to set Intervel property in milliseconds. That is, one second is equal to 1000 milliseconds. For example, if we want to set an interval of 1 minute we set the value at Interval property as 60000, means 60x1000 . By default the Enabled property of Timer Control is False. So before running the program we have to set the Enabled property is True , then only the Timer Control starts its function.
  • 101. Renas Rajab Rekany OOP 2018 100 In the following program we display the current time in a Label Control. In order to develop this program, we need a Timer Control and a Label Control. Here we set the timer interval as 1000 milliseconds, that means one second, for displaying current system time in Label control for the interval of one second. using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { label1.Text = DateTime.Now.ToString(); } } } Start and Stop Timer Control The Timer control have included the Start and Stop methods for start and stop the Timer control functions. Here we run this program only 10 seconds. In order to doing this ,in the following program we set Timer interval as 1000 (1 second) and check each seconds for stopping the Timer Control after 10 seconds.
  • 102. Renas Rajab Rekany OOP 2018 101 Code using System; using System.Windows.Forms; namespace WindowsFormsApplication2 { public partial class Form1 : Form { int second = 0; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { timer1.Interval = 1000; timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { label1.Text = DateTime.Now.ToString(); second = second + 1; if (second >= 10) { timer1.Stop(); MessageBox.Show("Exiting from Timer...."); } } } }
  • 103. Renas Rajab Rekany OOP 2018 102 Object Oriented Programming Structured programming is not the wrong way to write programs. Similarly, object-oriented programming is not necessarily the right way. Object-oriented programming (OOP) is an alternative program development technique that often tends to be better if we deal with large programs and if we care about program reusability. We make the following observations about structured programming: - Structured programming is narrowly oriented towards solving one particular problem - It would be nice if our programming efforts could be oriented more broadly - Structured programming is carried out by gradual decomposition of the functionality - The structures formed by functionality/actions/control are not the most stable parts of a program - Focusing on data structures instead of control structure is an alternative approach - Real systems have no single top - Real systems may have multiple tops [Bertrand Meyer] - It may therefore be natural to consider alternatives to the top-down approach OOP Concepts 1. Data Abstraction – it is the act of representing the essential features without including the background details. Data Hiding- it is a related concept of data abstraction. Unessential features are hidden from the world. 2. Data Encapsulation – it is the wrapping of data and associated functions in one single unit. 3. Inheritance – it is the capability of one class to inherit properties from other class. 4. Polymorphism – it is the ability for data to be processed in more than one form. 5. Modularity – it is the concept of breaking down the program into several module. E.g. : Classes, Structure, etc.
  • 104. Renas Rajab Rekany OOP 2018 103 Class Class: is an abstraction model used to define a new Data Type Which May Contain a Combination of encapsulating Data (Member Variable) Operation That Can Be Perform On Data (Member Function) And Accessory to Data (properties). Member Variable = Field Member Function = Method Properties = Attributes Declaration Class Class_name { [Properties] Member Variable; [Properties] Member Function; . . . } Class_name var = new Class_name (); ❖ Class can declared before or after main method ❖ Or can be declared before class program. ❖ we can change class program to any name What a class is Classes are the user defined data types that represent the state and behaviour of an object. State represents the properties and behaviour is the action that objects can perform. Classes can be declared using the following access specifiers that limit the accessibility of classes to other classes, however some classes does not require any access modifiers. 1. Public 2. Private 3. Protected 4. Internal 5. Protected internal To learn the details of access specifiers please refer to the following article of mine: • Access Modifiers in C#
  • 105. Renas Rajab Rekany OOP 2018 104 For example: public class Accounts { } Some Key points about classes • Classes are reference types that hold the object created dynamically in a heap. • All classes have a base type of System.Object. • The default access modifier of a class is Internal. • The default access modifier of methods and variables is Private. • Directly inside the namespaces declarations of private classes are not allowed. The following are types of classes in C#: What an Abstract class is An Abstract class is a class that provides a common definition to the subclasses and this is the type of class whose object is not created. Some key points of Abstract classes are: • Abstract classes are declared using the abstract keyword. • We cannot create an object of an abstract class. • If you want to use it then it must be inherited in a subclass. • An Abstract class contains both abstract and non-abstract methods. • The methods inside the abstract class can either have an implementation or no implementation. • We can inherit two abstract classes; in this case the base class method implementation is optional. • An Abstract class has only one subclass. • Methods inside the abstract class cannot be private. • If there is at least one method abstract in a class then the class must be abstract. For example: abstract class Accounts { }
  • 106. Renas Rajab Rekany OOP 2018 105 Partial Classes It is a type of class that allows dividing their properties, methods and events into multiple source files and at compile time these files are combined into a single class. The following are some key points: • All the parts of the partial class must be prefixed with the partial keyword. • If you seal a specific part of a partial class then the entire class is sealed, the same as for an abstract class. • Inheritance cannot be applied on partial classes. • The classes that are written in two class files are combined together at run time. For example: partial class Accounts { } Sealed Class A Sealed class is a class that cannot be inherited and used to restrict the properties. The following are some key points: • A Sealed class is created using the sealed keyword. • Access modifiers are not applied to a sealed class. • To access the sealed members we must create an object of the class. For example: sealed class Accounts { } Static Class It is the type of class that cannot be instantiated, in oher words we cannot create an object of that class using the new keyword, such that class members can be called directly using their class name. The following are some key points: • Created using the static keyword. • Inside a static class only static members are allowed, in other words everything inside thestatic class must be static. • We cannot create an object of the static class. • A Static class cannot be inherited. • It allows only a static constructor to be declared.
  • 107. Renas Rajab Rekany OOP 2018 106 • The methods of the static class can be called using the class name without creating the instance. For example: static class Accounts { } // Example 1 // Define Class point class coordinate { public int x; public int y; public void setx(int a) { x = a; } public void sety(int b) { y = b; } public int getx() { return (x); } public int gety() { return (y); } } // Calling the Class private void button1_Click(object sender, EventArgs e) { coordinate p = new coordinate(); p.x = 10; p.y = 5; p.setx(6); p.sety(7); textBox1.Text = Convert.ToString(p.getx()); textBox2.Text = Convert.ToString(p.gety()); } //Example 2 // Define Class circle class circle { double radius; double pi = 3.141; public double area() { return (radius * radius * pi); } public void set_r(double b)
  • 108. Renas Rajab Rekany OOP 2018 107 { radius = b; } } // Calling the Class private void button1_Click(object sender, EventArgs e) { circle c = new circle(); double x = Convert.ToDouble(textBox1.Text); c.set_r(x); textBox2.Text=Convert.ToString( c.area()); } //Example 3 // Class array Define and Sort class sort { int[] ar = new int[10]; public void set_array(int[] a) { ar = a; } public int[] get_array() { Array.Sort(ar); return ((ar)); } } // Calling the Class private void button1_Click(object sender, EventArgs e) { sort s = new sort(); int[] b = new int[10] { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; s.set_array(b); b=s.get_array(); for (int i = 0; i < 10; i++) { textBox1.Text = textBox1.Text + b[i]; } } Multi-Function in Class //Example 4 //Class class stage2 { double fp = 1; public double factx(int x) { for (int i = x; i > 0; i--) { fp = fp * i; } return(fp); } public double powx(int x,int y)
  • 109. Renas Rajab Rekany OOP 2018 108 { fp = Math.Pow(x, y); return (fp); } public string str_up(string a) {return (a.ToUpper());} public string str_dn(string a) {return(a.ToLower());} public string get_s; public string set_s; public void find_array(string[,] s) { for (int j = 0; j < 10; j++) if (get_s == s[0, j]) { set_s =s[2,j]+":"+s[0,j]+" = "+ s[1, j]; break; } } } // Calling the Class from Button private void button1_Click(object sender, EventArgs e) { string[,] st = new string[3, 10] { { "AA", "AB", "AC", "AD", “…….. stage2 s2 = new stage2(); if (comboBox1.Text == "factorial") { int x = Convert.ToInt32(textBox1.Text); textBox2.Text = Convert.ToString(s2.factx(x)); } else if (comboBox1.Text == "power") { int x = Convert.ToInt32(textBox1.Text); textBox2.Text = Convert.ToString(s2.powx(x, x)); } else if (comboBox1.Text == "upper") { string s = textBox1.Text; textBox2.Text = s2.str_up(s); } else if (comboBox1.Text == "lower") { string s = textBox1.Text; textBox2.Text = s2.str_dn(s); } else if (comboBox1.Text == "find") { s2.get_s = textBox3.Text; s2.find_array(st); textBox4.Text = s2.set_s; } }
  • 110. Renas Rajab Rekany OOP 2018 109 Constructor Constructor: Is a special method used when an object of class is created, and is called automatically in order to initialize a new instance of a class Constructor properties ‽ Constructor has the same name of the class. ‽ Constructor does not return value. ‽ Constructor can be overloaded. ‽ Constructor has public access. ➢ Default Construction: has no parameters list. ➢ Parameter Construction: has parameters list. ➢ Copy Construction: has object parameter type. //Example 5 //Class class pickup { string model; double speed; public pickup() // Default Construction { model = ""; speed = 0; } public pickup(string s, double d) // Parameter Construction { model = s; speed = d; } public pickup(pickup k) // Copy Construction { model = k.model; speed = k.speed; } } //Button private void button1_Click(object sender, EventArgs e) { pickup c1 = new pickup(); // Default Construction pickup c2 = new pickup("toyota", 220); // Parameter Construction pickup c3 = new pickup(c2); // Copy Construction } Copy constructors: can be used for making copies of existing objects. A copy constructor can be recognized by the fact that it takes a parameter of the same type as the class to which it belongs. Object copying is an intricate matter, because we will have to decide if the referred object should be copied too (shallow copying, deep copying, or something in between,
  • 111. Renas Rajab Rekany OOP 2018 110 Destructor Since C# is garbage collected, meaning that the framework will free the objects that you no longer use, there may be times where you need to do some manual cleanup. A destructor, a method called once an object is disposed, can be used to cleanup resources used by the object. Destructor doesn't look very much like other methods in C#. Here is an example of a destructor for our Car class: ➢ Is a method called once an object is disposed, can be used to cleanup recourse used by the object. ➢ Destructors only used with classes. ➢ A class can only have one destructor. ➢ Destructor cannot be inherited or overloaded. ➢ Destructor cannot be called, They are invoked automatically. ➢ Destructors cannot take a modifiers or have parameters. ~rain () { MessageBox.Show("car object is dead"); } //Example 6 //Class class company { string model; double speed; public company() // Default Construction { model = ""; speed = 0; } public company(string s, double d) // Parameter Construction { model = s; speed = d; } public company(company k) // Copy Construction { model = k.model; speed = k.speed; } public ~ company() // Destructor {MessageBox.Show(" Destructor "); } } //Button private void button1_Click(object sender, EventArgs e) { company c1 = new company(); // Default Construction company c2 = new company("toyota", 220); // Parameter Construction company c3 = new company(c2); // Copy Construction }
  • 112. Renas Rajab Rekany OOP 2018 111 Accessibility Keywords All types and type members have an accessibility level, which controls whether they can be used from other code in your assembly or other assemblies. You can use the following access modifiers to specify the accessibility of a type or member when you declare it: 1. Public: The type or member can be accessed by any other code in the same assembly or another assembly that references it. 2. Private: The type or member can be accessed only by code in the same class or structure. 3. Protected: The type or member can be accessed only by code in the same class or structure, or in a class that is derived from that class. 4. Internal: The type or member can be accessed by any code in the same assembly, but not from another assembly. Public The public keyword is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members. Accessibility: 1. Can be accessed by objects of the class 2. Can be accessed by derived classes Note: In the following example num1 is direct access. //Example 7 //Class class Program { class AccessMod { public int num1; int num2; } //Button private void button1_Click(object sender, EventArgs e) { AccessMod ob1 = new AccessMod();