C# - Chapter 2
C# - Chapter 2
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.
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…
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.
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 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.
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.
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";
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.
In this example, the statement, number +=5; will be executed only if the value of the number
is less than 5.
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;
}
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);
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();
And when the above program run would produce output like shown in the following picture:
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);
}