0% found this document useful (0 votes)
105 views

C# - Chapter 2

This document provides an introduction to creating graphical user interface (GUI) applications using C# and Windows Forms. It discusses key features of C#, how to set up a basic Windows Forms project in Visual Studio, and some common controls like labels and buttons. It emphasizes that GUI apps are event-driven, and that events need to be handled through event handlers to make the application interactive and responsive to user input. The document uses examples to demonstrate how to add controls visually, set their properties, and write code handlers for events like a button click.

Uploaded by

amanuel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views

C# - Chapter 2

This document provides an introduction to creating graphical user interface (GUI) applications using C# and Windows Forms. It discusses key features of C#, how to set up a basic Windows Forms project in Visual Studio, and some common controls like labels and buttons. It emphasizes that GUI apps are event-driven, and that events need to be handled through event handlers to make the application interactive and responsive to user input. The document uses examples to demonstrate how to add controls visually, set their properties, and write code handlers for events like a button click.

Uploaded by

amanuel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Chapter 2

Introduction to Application development using C#


2.1. Fundamentals and Features
Although C# constructs closely follow traditional high-level languages, C and C++ and being an
object oriented programming language. It has strong resemblance with java, it has numerous
strong programming features that make it endearing to a number of developers worldwide.
The following is a list of a few important features of C# language.
 Automatic Garbage Collection
 Large set of standard library
 Assembly versioning
 Properties and events
 Delegates and event management
 Easy to use Generics
 Indexers
 Conditional compilation
 Simple multithreading
 LINQ and Lambda expression
 Integration with windows
The .Net framework and C# enables you to create the following types of applications easily
through the use of the standard class libraries provided by the .Net framework, some of the
applications you can create with C# are:
 Web applications (web sites).
 Windows graphical user interfaces (GUI)
 Console based applications.
 Class libraries and stand-alone components (.dLL files),
 And services can also be created with C#.
C# was designed with the internet applications in mind, you can quickly build applications that
run on the web with C#, using for example web forms: which are part of ASP.Net (Active Server
pages.).
You can also develop windows forms applications, which are applications designed for the
desktop, those applications use classes that are part of System.Windows.Form namespace.
Those types of applications can include menu’s pictures, dropdown controls, buttons, textboxes
and labels. Visual studio also provides easy drag and drop features which makes it easy to design
and develop windows forms applications fast.
The other common type of application you can create with C# are console applications, those
type of applications normally send requests to the operating system, display text on the command
console. Those types of applications are the easiest to create, simplest approach to learning
software development, and minimal overhead for input and output of data. Console programs are
easy to develop, because console based applications perform all their input and output at the
command line, they are ideal for quickly trying out language features and writing command-line
utilities.
Visual studio is the integrated development environment in which developers work when
creating in one of the many languages, including C#, it is used to create console and graphical
user interface (GUI) applications.
Microsoft Visual Studio is a powerful IDE that ensures quality code throughout the entire
application lifecycle, from design to deployment. Some windows are used for writing code, some
for designing interfaces, and others for getting a general overview of files or classes in your
application. Microsoft Visual Studio includes a host of visual designers to aid in the development
of various types of applications. These tools include such as Windows Forms Designer, WPF
(Windows Presentation Foundation) Designer, Web development, Class designer, Data designer
and Mapping designer.

2.2. Introduction to GUI


Combined with the .Net Framework, C# enables the creation of windows applications, web
services, database tools, components, controls and more. Visual studio organizes you work in
projects and solutions. A solution can contain more than one project, such as a DLL and an
executable that references that DLL.
Graphical User Interfaces are one of the many types of applications that you can create with C#.
GUI’s are applications that display graphical elements to users, this types of applications allow
easier interaction for end users when interacting with computer applications, since this types of
applications allow the user to control and operate computer programs through a set of controls
such as buttons, text boxes, dropdowns etc… which are used as a front end for a computer
application/programs and they are easier for end users to manipulate and operate.
Graphical user interfaces (GUI) includes a set of controls such as: Menus, Text in many sizes
and colors, buttons and many other controls (pictures, dropdowns, checkboxs etc…).
The most common way of creating windows GUI applications is through the use of windows
forms application,
2.2.1. C# and Windows Forms
C# has all the features of any powerful, modern language. In C# the most rapid and convenient
way to create your user interface is to do so visually, using the windows forms designer and
toolbox. Windows forms controls are reusable components that encapsulate user interface
functionality and are used in client side windows based applications.
A control is a component or a form, used to display information or accept user input. The
Control class provides the base functionality for all controls that are displayed on a Form.
To create windows forms application you would have to reference and import
System.Windows.Forms namespace, windows forms application offers many controls which also
has many properties that you can set and customize their values which includes: Text, Color,
Font and Location of the controls.
Windows forms applications has an extensive collection of control classes, the top level window
for an application is called a Form. The Microsoft visual studio ide makes it easy to design
windows forms applications. Here is an example of how a simple windows forms applications
would look:

Creating and adding controls to a windows forms application


We start by opening the visual studio development environment and creating a new windows
forms application. The following pictures shows the process.
Choose a name for your windows forms project and click OK. And we will get the following
screen.

Now you can add any controls to your form from the toolbox panel shown on the left by
dragging and any control and dropping it onto the form.
Now if we run the application, we would see a window similar to the following:

You can control a Control’s set of properties easily using the properties panel found on the lower
right part of the visual studio environment. The following picture shows using the properties
panel to set the text displayed on the button we added into the form above.
As you can see you can you can set the set of supported properties that a control such as the
button has using the properties panel easily, but that is not the only way of controlling the
properties, you can also set the properties with coding.
Right click on the form and click on the view code or press the f7 key to go the C# code of the
form. Add the code as the shown in the following picture.

As you can see you can also control the properties using code. But most of the time the
properties panel is used to control the set of the properties that a control component has,
controlling the properties using code is mostly used when some events occur such as when the
users presses a button and in response to the button press/click event some controls property
changes.
The 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 control/class is defined in the
System.Windows.Forms namespace.
To use the label control, you would drag the label from the toolbox into your windows forms
application project. To set its text property you can use the properties panel or you can set the
text using code like the following.

label1.Text = “This is my first label control”

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 properites. And you can also set
other properties of the Label control such as TextAlign, font etc…

The Button Control


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. You can use the
button control in your windows forms application by dragging it from the toolbox and dropping
it into your form.
As we have created the above applications, we have used to the button control, but a button that
we have used above does nothing when clicked. For buttons to work we need to set and handle
their different events, such as click event, mouse hover event, and mouse enter etc….

2.2.2. Understanding C# GUI Events


GUI applications are interactive, for our windows forms application to be useful we need to them
interactive, for windows forms applications to be interactive we need to set and handle different
events that occur.
GUI applications are mostly event-driven, the basic idea behind event-driven programming is
that: the program waits for some events to occur and then responds some actions based on the
events that fired up.
An event is a message that tells the program that something has happened. For example, if the
user clicks a button, then the event is generated, and it tells the program that the particular button
was clicked, and then the program can perform some actions associated with the event.
An event is the change in the state of an object, events are mostly generated as a result of user
interaction with the graphical user interface components. For example: clicking for a button,
moving the mouse, entering characters through the keyboard, selecting an item from a list,
scrolling the page, etc….
To create event-driven GUI applications you need to be able to listen for and handle the events
that occur to windows forms controls/components.
For example if you want to respond to a particular button’s click event you need to create an
event handler for that particular button.
An event handler is code that can sense/listen for an event and respond to it. The C# IDE visual
studio can generate the “shell” of the code to respond to events such as click events etc…
Let’s see in the following picture, how we would set the button click event in a GUI application.
Create a windows forms application as we have done before. And add the button control to your
form, set the text property to “Click Here” and can also customize its size its, background color
etc… using the properties panel.

To set an event handler for the button click event of the button, you can double click button
control and an event handler code is automatically generated, now you can code the action you
want to be performed when the button is clicked. After you double click the button to generate a
method similar to the following is created and you would put the action there.
Now if you run the project and click on the button you would see an output similar to the
following picture.

You can also set event handlers using code, but using the designer is commonly used to set event
handlers.
Here is an example of setting event handlers using code. You can add an event handler, for
example in the constructor of your form.
button1.Click += eventHandlerMethodName;
The eventHandlerMethodName must have void return type, and takes two arguments
sender:object, and e:EventArgs.
Or button1.Click += new EventHandler(methodName);

Or you can let visual studio generate this method by writing button1.Click += and then pressing
tab key.
As you can see it is easy to add event handlers to windows forms control components. And
visual studio helps you to easily handle events.
Now that we know how to add event handlers and perform some actions lets create an
application which controls the background color of the form based on the buttons clicked.
Create a new project and add three buttons to the form, set their FlatStyle to Flat and their text to
empty string, and their BackColor property to any color you want.

Now add the event handlers for the buttons you created and then write the code which changes
the backColor property of the form to the BackColor property of the button that was clicked.
The TextBox Control
A text box control is used to display, or accept as input, a single line of text. This control has
additional functionality that is not found in the standard windows text box control, including
multi-line editing and password masking.
You can set the text box control properties through the properties panel and programmatically.
You can control properties such as the width, height, background and foreground properties of
the text box control. You can also add event handlers to the text box control just like you did for
the button control, the text box control has events such as keydown which allows you to capture
which key the user pressed, the TextChanged event which fires up when the text inside the text
box control as been changed. You can also limit the number of characters or words a user can
insert into a text box control using the MaxLength property, you can also set the ReadOnly
property to true if you don’t allow the text inside a text box control to be modified by the user.
And you can add the KeyDown event handler using the properties window, by first clicking the
lightening icon and finding the event name KeyDown and double click it to add an event handler
for it.

The ComboBox Control


C# controls are located in the Toolbox of the development environment, and you use them to
create objects on a form with a simple series of mouse clicks and dragging motions. A
Combobox displays a text box combined with a ListBox, which enables a user to select items
from the list or enter a new value.
You can add the list of items in the combo box control using the Items property, and through
code like the following.
comboBox1.Items.Add(“Thursday”); And you can also remove items
using the remove method.
comboBox1.Items.Add(“Friday”);
Now if you run the application you would see an output similar to the following and clicking the
button outputs a messagebox with the selected item from the combobox control.
As you can see with C# and the windows forms application it is easy to develop desktop GUI
based applications and the environment provides you a lot of controls that you can use in your
GUI based desktop applications.

2.2.3. Top Level Menus


A menu bar is the one of the most visible parts of the GUI application. It is a group of commands
which stores a collection of menu items which perform sets of actions. To use Menus in C# you
would use MenuStrip control to hold the every menu items grouped and the MenuItem control
which represents the single menu items and can also be used to group a set of related menu items
together. You can drag and drop the MenuStrip control from the tool box and start typing in the
place where is says ‘Type here’ and visual studio automatically creates the menu items for you.

And then you can add the event handlers the same way we added event handlers to the other
controls, by double clicking the menu items, through the properties panel, or programmatically.
Let’s extend this application and create a simple text editor capable of opening text files and
saving text files.
Drag and drop a RichTextBox control to the form and set its dock property to fill (click on the
caret at the right top of the control and click on dock to parent). And you can customize the font
and other properties as well.
Now add an event handler for the save menu item, by double clicking on it.
And add the following code to the event handler.
As you can see it is easy to save files in windows forms application, with just a few lines of code
we are able to save text files. Here we are using a SaveFileDialog box and show it to the user and
if the user fills in a filename and click save, then we create a StreamWriter object passing the
path of the file which the user has chosen, write the text written in the rich text box control into
the file, and call the flush() method to clear all buffers for the writer object and write all buffered
data to the underlying stream.
Now our application saves text written in the rich text box by clicking the save command/menu
item found under the file menu item, we now can also add a shortcut to the save menu (usually
used shortcut key is CTRL + S). select the save menu item and in the properties panel find
ShortcutKeys properties and it to CTRL + S. and test the application and use the shortcut to save
file that you have written.

Now let’s implement the file open functionality. We can start by setting a shortcut (which is
usually CTRL+O).
And add the event handler for the Open file menu item. And add the following code.
Here to open a file, we have created a StreamReader object, the object is used to read character
based streams, we then read all the text in the file and set the rich text box’s text to the file’s
content.
Now run and test the application, the application works fine, but there are small problems such
as, the save file functionality saves a file as it was never opened before, and let’s also add a save
file as functionality.

Add an event handler for the save file as and modify the code as follows.
Add the following two properties/fields to you form class.

And initialize them to their default values as follows in the constructor.

Create two methods in the form class as follows.


Update the save file menu item event handler as follows.

And then add and update open file menu item, and save file as menu item event handlers as
follows.
Now run and test the application, we now have a simple working text editor application. Let’s
extend the application with some useful functionality such as a status bar which displays some
helpful information about the text editor.

Then update your code as follows.


Add this code to the SaveFile
method.

And add this code to the open file


menu item click event handler.
As you can see C# and the visual studio environment makes it easy to develop windows desktop
applications. Now feel free to extend the text editor application you created above.

2.2.4. Context Menu


A context menu is shortcut menu, which gets to be displayed when the user right clicks on the
associated control. It is useful as it groups a set of usually used sets of commands as a shortcut
and it is easily accessible.
To add context menu into your application, you can click ContextMenu from the toolbox which
is under menus and toolbars sub list and drag it over to your form. In this example let’s add the
context menu to the text editor which we created above, for the rich text box control. After you
added a context menu into your form the next step would be to set the context menu property of
the rich text box control to the context menu we just added. Adding click event handler to a
context menu is similar to the other controls we have seen so far, just double click the item and
code the action to be performed in the method generated.

Here is the code for the context menu items we added to our rich text box control.
As you can see the rich text box already has methods for the standard copy, cut, undo and redo
operations, we just only had to call the methods.
Now run and test the application right click on the text editor (rich textbox control) and see if the
menu items in the context menu works. Now implement the paste option on the context menu.

2.2.5. Building Toolbars


A tool bar is like a container which can be used to group of different types controls, and other
user interface elements that support many appearance options and that support overflow if the
controls exceed the toolbar and run-time items reordering.
In windows based application you can add and use toolbars easily through the toolbox, the
toolbar is recognized as ToolStripe class in C# and you can drag and drop it from the toolbox.
Let’s add a toolbar to out text editor and see how we can use them. If after you added the
ToolStripe control, the rich text box control hides behind right click on the rich text box and
click on the bring to front menu item.
Let’s add a button and set its image. Select the button from the designer and find the property
Image in the properties panel, click on the three dots. In the dialog box that pops up click the
import button and import the image you want to use in your project. And as you can see we have
changed the image property on the button.

Now let’s add a click event handler for the button the same way we did before. and then update
the code as follows.
2.3. Drawing Graphics in C#
In C# programmers are free to construct whatever shapes and images they desire. The intelligent
and well planned use of graphical output can produce some phenomenal improvements in
software. Not only does graphics make sense of massive amounts of output produced by
programs that model complex physical, social and mathematical systems. Finally there are many
applications of computers that would simply be impossible without the ability output visually.
Applications such as virtual reality, computer aided design/ computer aided manufacturing
(CAD/CAM), games and entertainment, medical imaging and computer mapping would not be
anywhere near as important as they are without the enormous improvements that have occurred
in the areas of graphics and visualization.
To control the setting and clearing of pixels, programmers use a collection of functions that are
part of a special software package called a graphics library. Virtually all modern programming
languages, including C#, come with an extensive and powerful graphics library for creating
different shapes and images. Typically an “industrial strength” graphics library includes
hundreds of functions for everything from drawing simple drawing shapes like lines, circles, to
creating and selecting colors, to more complex operations such as displaying scrolling windows,
pull-down menus and buttons.
To use C# graphics library to draw different shapes, you first have to create a windows forms
application project, let’s create the project go the code view of the form1 window, you can do
this by right clicking on the form and click on the view code.
In C# to be able to create and use graphics you would usually use the graphics class which is
under the System.Drawing namespace, the System.Drawing namespace is automatically
imported.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// code to actually draw shapes woudl be written here.
}
}

Now let’s add some code to draw a line to the form window.
public Form1()
{
InitializeComponent();
this.Text = "C# Graphics programming";
//createa a graphics object/ a drawing canvas which is actually the surface
of the form.
Graphics drawingCanvas = CreateGraphics();
//causes the form to be displayed on the screen.
Show();
//creates a tool, in this case a pen,that will 'paint' the lines on the
screen.
Pen blackPen = new Pen(Color.Black, 2);
// the following line, is the code which actually draws the line, it takes
the pen to use,
//the x and y cooordinates where the drawing begins and another x and y
coordinates where the drawing ends.
drawingCanvas.DrawLine(blackPen,20, 20, 100, 100);

The above code, when run displays a form with a line drawn on the form.

public Form1()
{
InitializeComponent();
this.Text = "C# Graphics programming";
//createa a graphics object/ a drawing canvas which is actually the surface
of the form.
Graphics drawingCanvas = CreateGraphics();
//causes the form to be displayed on the screen.
Show();
//creates a tool, in this case a pen,that will 'paint' the shapes to be drawn
on screen.
Pen blackPen = new Pen(Color.Black, 2);
// the drawRectangle method is used to draw a rectangle.
drawingCanvas.DrawRectangle(blackPen, 25, 60, 50, 40);

}
As you can see C# and the .Net platform provides an easy to use graphics library.
You can also draw an ellipse/circle using the DrawEllipse method.
public Form1()
{
InitializeComponent();
this.Text = "C# Graphics programming";
//createa a graphics object/ a drawing canvas which is actually the surface
of the form.
Graphics drawingCanvas = CreateGraphics();
//causes the form to be displayed on the screen.
Show();
//creates a tool, in this case a pen,that will 'paint' the shape to be drawn.
Pen chocolatePen = new Pen(Color.Chocolate, 2);
// the DrawEllipse method is used to draw a a circle/ellipse.
drawingCanvas.DrawEllipse(chocolatePen, 30, 30, 125, 125);

The above code would result with similar output as the following screen.
Not only can you draw shapes, you can also draw strings using DrawString(string,font,brush,x,y)
method. The string is the string to be output, using the font specified, drawing with the brush
specified, and beginning at the pixel position (x, y) for the upper-left corner of the bounding
rectangle for the text. The following shows an example with the text ‘Stop’ drawn inside of a
circle.
public Form1()
{
InitializeComponent();
this.Text = "C# Graphics Programming";
Graphics drawingCanvas = CreateGraphics();
Show();
Pen blackPen = new Pen(Color.Black, 2);
drawingCanvas.DrawEllipse(blackPen, 160, 160, 40, 40);
Brush redBrush = Brushes.Red;
Font f = new Font("Arial", 10);
drawingCanvas.DrawString("Stop",f,redBrush,165,170);
}

In summary we have the following and some other additional graphics methods/functions at out
disposal.
 DrawLine(Pen,x1,y1,x2,y2)
 DrawRectangle(Pen, x, y, x, width, height)
 DrawEllipse(Pen, x, y, width, height)
 DrawString(string, font, brush, x, y)
In addition to those draw methods, the graphics library also provides some fill methods, which
fills in a some shape in some color, such as FillEllipse() and FillRectangle().
Now that forms and graphics are available, we seem close to producing elements of a typical
GUI. Can we draw a button that acts like a button on a real GUI form, that is can we write code
to sense mouse click on that button and respond with some action?
As we have seen GUI event handling section, to sense events such as mouse clicks in a C#
windows form, an ‘event handler’ must be created.
Here is a code which draws a circle and inside of the circle we are drawing a string which says
‘Ok’ and then later on we will add something like a click event for the graphics we created.
public Form1()
{
InitializeComponent();
this.Text = "C# Graphics Programming";
Graphics drawingCanvas = CreateGraphics();
Show();
Pen blackPen = new Pen(Color.Black, 2);
drawingCanvas.DrawEllipse(blackPen, 100, 100, 60, 60);
Brush redBrush = Brushes.Red;
Font f = new Font("Arial", 13);
drawingCanvas.DrawString("OK",f,redBrush,115,120);
}
Now to add something like a click event, let’s add a click event for the form and check where the
cursor was at the time of the mouse click event and if it match’s the area of our button we we
display a message box says ‘clicked the button’ and displays the message ‘clicked outside of the
button’. To add the mouse click event listener for the form, you can right click on the form and
choose properties and now click on the events button (the lightening-bolt) find and double click
the event which says MouseClick. And a method will be generated on your code, now update he
code as follows.
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
int x = e.X;
int y = e.Y;
if ((x >=100 &&x <=160) && (y >= 100 && y <= 160))
{
MessageBox.Show("cliked the button");
}
else
{
MessageBox.Show("clicked outside of the button");
}

Running the project and test it, see what happens when you click on the graphics object we
created.
Let’s create a new windows forms application create some interesting images. Update the forms
constructor as follows.
/// <summary>
/// creates a graphics image, which represents a house.
/// </summary>
public Form1()
{
InitializeComponent();
this.Text = "C# Graphics programming";
Graphics drawingCanvas = CreateGraphics();
Show();
Pen BlackPen = new Pen(Color.Black, 2);
// draws the rectanle (the house)
drawingCanvas.DrawRectangle(BlackPen, 50, 110, 200, 150);
//draws a rectangle, the window on the left part of the house.
drawingCanvas.DrawRectangle(BlackPen, 60, 120, 40,40);
// draws a rectangle, the window on the right part of the house.
drawingCanvas.DrawRectangle(BlackPen, 200, 120, 40, 40);
//draws a rectangle, the door of the house.
drawingCanvas.DrawRectangle(BlackPen, 125, 180, 50, 80);
// draws a line which forms the left part roof of the house
drawingCanvas.DrawLine(BlackPen, 50, 110, 150, 10);
// draws a line which forms the right part roof of the house
drawingCanvas.DrawLine(BlackPen, 250, 110, 150, 10);
// draws an ellipse/circle, the doornob of the house.
drawingCanvas.DrawEllipse(BlackPen, 165, 215, 5, 5);

Running the project would produce output similar to the following screen.
Another way of drawing graphics in windows forms application is using the Paint event of the
Form class. Basically you would create a new event handler for the Paint event and use the
graphics object which comes in under the EventArgs parameter. Here is an example:
public Form1()
{
InitializeComponent();
this.Text = "C# Graphics Programming";

this.Paint += new PaintEventHandler(paintGraphics);

private void paintGraphics(object sender, PaintEventArgs e)


{
Graphics g = e.Graphics;
g.FillRectangle(Brushes.DarkOrange, new Rectangle(40, 40, 130, 130));
}

In addition to the System.Drawing namespace, you can also import the


System.Drawing.Drawing2D namespace.
The System.Drawing.Drawing2D namespace provides advanced techniques for manipulating
Pen and Brush objects. For example you can change the look and feel of lines by applying the
values of DashStyle Enumerator (like Dash, DashDot etc…).
Also by making use various Brush classes like SolidBrush, HatchStyleBrush etc you can modify
the appearance of filled shapes. For instance, a rectangle can be filled with a vertical and
horizontal lines. As already examined a normal shape (using the DrawXX methods) accept a Pen
object argument besides the floating point values while a filled shape (using the FillXX
methods ) accepts a brush class argument.

Working with Pen objects


As we have used before the pen object is used to draw lines and curves. And as we have
discussed above there are some additional objects used to manipulate the pen and brush objects
defined in the System.Drawing.Drawing2D, here is an example:
public Form1()
{
InitializeComponent();
this.Text = "C# Graphics Programming";
this.Paint += new PaintEventHandler(paintGraphics);

private void paintGraphics(object sender, PaintEventArgs e)


{
Graphics g = e.Graphics;

Pen penLine = new Pen(Color.Red,5);


penLine.DashStyle = DashStyle.Dash;
g.DrawLine(penLine, 50, 50, 100, 100);
}
And it would produce something like the following.

Working with Brush objects


Brush objects are used to fill shapes with a given color, pattern or image. There are mainly five
types of Brushes like: SolidBrush (default brush), HatchStyleBrush, LinearGradientBrush,
We will see examples of those different brushes and apply them in a FillXX() method.
Create a windows forms application project, and then create a user control, you can create user
controls by right-clicking the either the solution or project and choose add and there you will find
a user control click on it will create a user control for you.
A user control (UserControl class), provides an empty control, which can be used to create
custom controls. We have named the user control GraphicBtnUserControl.
You can use the user control we created by just dragging and dropping it into any form easily.
we have used user controls to draw graphic shapes into, using user controls to create custom
controls, or graphics is the preferred way of creating controls, or custom graphics as it provides
separation, and most importantly reusability, the example we created above now allows you to
use the user control in many different forms or even different projects with the graphics we
drawn into it.
And in the example above we have used different brushes such as the default brush (SolidBrush),
the LinearGradientBrush and the HatchBrush, you can also comment out the line which has the
linear gradient brush and uncomment the line which has the HatchBrush if you want to test out
the HatchBrush bursh type. And don’t forget to import the System.Drawing.Drawing2D
namespace.
When the above program is run, it has an output similar to the following screen. And when you
click on it gives a message saying that the button was clicked.
2.4. Controlling Program Execution
The actions that a program takes are expressed on statements. Common actions include declaring
variables, assigning values, calling methods, looping through collections, and branching to one
or another block of code, depending on a given condition.
The order in which statements are executed in a program is called the flow of control or flow of
execution. The flow of control may vary every time the program is run, depending on how the
program reacts to the input that it receives at run time.
A statement can consist of a single line of code that ends in a semi-colon, or a series of single-
line statements in a block. A statement block is enclosed in {} brackets and can contain nested
blocks.
Testing a condition is inevitable in programming. We will often face situations where we need to
test conditions (whether it is true or false) to control the flow of execution of programs. These
conditions may be affected by user’s input, time factor, current environment where the program
is running etc…
Conditional, iteration, jump, and exception handling statements control a programs flow of
execution.
A conditional statement can decide something using keywords such as if, switch
An iteration statement can create a loop using keywords such as do, while, for, foreach and in.
A jump statement can be used to transfer program control using keywords such as break,
continue, return and yield etc…

2.5. Decision Making and Branching and Loops


Decision making statements
Branching or decision making statements allow a program to branch to one or another block of
code, depending on a given condition. The order in which statements are executed in a program
is called the flow of control or flow execution. The flow of control may vary every time that a
program is run, depending on how the program reacts to input that it receives at run time.

C# If (If-then) Statements
C# if statements will execute a block of code if the given condition is true. The syntax of an if
statement is.

 The Boolean expression will return either true or false.


 If the Boolean expression returns true, the statements inside the body of the if (statements
inside the {} braces) will be executed.
 If the Boolean expression returns false, the statements inside the {} braces will be
ignored.
For example:

In this example, the statement, number +=5; will be executed only if the value of the number
is less than 5.

How the If- statement works?

class Program
{
static void Main(string[] args)
{
int myNumber = 5;
if(myNumber == 4)
{
Console.WriteLine("This will not be shown because myNumber is not 4.");
}
else if (myNumber < 0)
{
Console.WriteLine("This will not be shown because myNumber is not
nagative");
}
else if (myNumber%2 == 0)
{
Console.WriteLine("This will not be executed because myNumber is not
even");
}
else
{
Console.WriteLine("myNumber does not match the coded conditions, so this
statement will be shown,executed");
}
Console.readLine();

}
}

Also note that C# if statements similarly like other c-like programming languages can be nested,
means that you can write if statements inside of if statements.

C# Switch statements
The switch statement is similar to the statement from C, C++, and Java, unlike C, each case
statement must finish with a jump statement (that can be break or goto or return). In other words
C# does not support ‘fall through’ from one case statement to the next (thereby eliminating) a
common source of unexpected behavior in C programs). However ‘stacking’ of cases is allowed,
as in the example below, if goto is used it may refer to a case label or the default case (e.g. goto
case 0, or goto default).
The default label is optional if no default case defined, then the default behavior is to do nothing.
static void Main(string[] args)
{
int nCPU = 8;
switch (nCPU)
{
case 0:
Console.WriteLine("You Don't have a CPU");
break;
case 1:
Console.WriteLine("Single Processor computer");
break;
case 2:
Console.WriteLine("Dual Processort computer");
break;
case 3:
//falls through
case 4:
//falls through
case 5:
//falls through
case 6:
//falls through
case 7:
//falls through
case 8:
Console.WriteLine("A multi-processor computer");
break;
default:
Console.WriteLine("A seroiusly parallel computer");
break;
}
}

A nice improvement over the C switch statement is that switch variable can be a string.
Console.Write("Enter a domain name: ");
string domain = Console.ReadLine();
domain = domain.Trim().ToLower();

switch (domain)
{
case "us":
Console.WriteLine("United States");
break;
case "de":
Console.WriteLine("Germany");
break;
case "et":
Console.WriteLine("Ethiopia");
break;
default:
Console.WriteLine("Unknown");
break;
}

Loops (Iteration statements)


An iteration statement creates a loop of code to execute a variable number of times, the for loop,
the while loop and the foreach loop are the iteration statements that are supported by C#.
Do… while loop
The do… while loop likewise has the same syntax as in other programming languages derived
from C. it is written in the following form:

do {
//body of the loop
}while(conditon);
The condition is any Boolean expression.
The do… while loop executes at least once even if the condition is false. After its first run it
evaluates its condition whether to run its body again. If the condition is true the body executes, if
the condition is false the do… while loop ends.
int count = 0;
do
{
Console.WriteLine("Count is: {0}",count);
} while (count !=0);

the above statement inside the do while loop executes, even if the condition is false, at
least once and exits out of the loop because the condition becomes false.

int num = 0;
do
{
Console.WriteLine(num++.ToString());
} while (num <=10);

The above example prints the numbers starting from 0 up to 10 (inclusive).


For loops
The for loop likewise has the same syntax as in other languages derived from C. it is written in
the following form.
When the number of cycles is known before the loop is initiated, we can use the for loop
iteration statement. In the following example we create/declare a counter variable (i) which is
automatically increased or decreased in value during each iteration of the loop.
A for loop has three phases: initialization, condition, and an optional increment/decrement and a
code block.
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i.ToString());
}
Console.ReadLine();

A for loop can be used for traversal of an array. From the length property of an array, we know
the size of an array.
string[] planets =
{"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Pluto"};
for (int i = 0; i < planets.Length; i++)
{
Console.WriteLine(planets[i]);
}
Console.WriteLine("In Reverse");
for (int i = planets.Length - 1; i >= 0; i--)
{
Console.WriteLine(planets[i]);
}
Console.ReadLine();

In the first for loop:


for (int i = 0; i < planets.Length; i++)
{
Console.WriteLine(planets[i]);
}
The array is accessed by a zero-based indexing. The first item has index 0. Therefore, the i
variable is initialized to zero. The condition checks if the I variable is less than the length of the
array. In the final phase, the i variable is incremented.
In the second for loop:
for (int i = planets.Length - 1; i >= 0; i--)
{
Console.WriteLine(planets[i]);
}
This for loop prints the elements of the array in reverse order. The i counter is initialized to the
array size. Since the indexing is zero based, the last element has index array size-1. The
condition ensures that the counter is greater or equal to zero. (array indexes cannot be negative).
In the third step the i counter is decremented by one.
Nested for loops
For statements can be nested. I.e. a for loop statement can be placed inside another for statement.
All cycles of a nested for loop are executed for each cycle of the outer for loop.
Here is an example of nested for loops:
string[] a1 = {"A","B","C"};
string[] a2 = { "A", "B", "C"};
for (int i = 0; i < a1.Length; i++)
{
for (int j = 0; j < a2.Length; j++)
{
Console.WriteLine(a1[i]+a2[j]);
}
}

And when the above program run would produce output like shown in the following picture:

In this example, we create a Cartesian product of two arrays.


string[] a1 = {"A","B","C"};
string[] a2 = { "A", "B", "C"};
We have two arrays. Each of the arrays has three letters, a Cartesian product is when each of the
elements from one array is paired with all the elements of the other array. To achieve this, we use
a nested loop.

C# foreach statement
The foreach construct simplifies traversing over collection of data. It has no explicit counter. The
foreach statement goes through the array or collection one by one and the current value is copied
to a variable defined in the construct.
Here is the example:
static void Main(string[] args){
string[] planets = {
"Mercury","Venues","Earth","Mars","Jupiter","Saturn","Urans","Neptune" };
foreach (string planet in planets)
{
Console.WriteLine(planet);
}

The usage of the foreach statement straightforward. The planets is an array that we iterate
through. The planet is a temporary variable that has the current value from the array. The foreach
statement goes through all the planets and prints them in the console.
C# break statement
The break statement can be used to terminate a block defined by while, for, or switch statements.
Random random = new Random();
while (true)
{
int num = random.Next(1, 30);
Console.Write("{0}",num);
if (num == 20)
{
break;
}
}
Console.WriteLine();

We defined an endless while loop. We use the break statement to get out of this loop. We choose
a random value from 1 to 30. We print the value. If the value equals to 20, we finish the endless
while loop.
C# continue statement
The continue statement is used to skip a part of the loop and continues with the next iteration of
the loop. It can be used in combination with the for and while statement. In the following
example, we will print a list of numbers that cannot be divided by 2 without a remainder (odd).
int number = 0;
while (number < 100)
{
number++;
if(number%2 == 0)
{
continue;
}
Console.WriteLine("{0}",number);
}

We iterate through 1,….99 with the while loop.


if(number%2 == 0)
{
continue;
}
If the expression num%2 returns 0, the number in question can be divided by 2. The continue
statement is executed and rest of the cycle is skipped.

You might also like