Be Sharp With C# (Chapter 1, Controls and Code)
Be Sharp With C# (Chapter 1, Controls and Code)
1
Controls and Code
Key concepts
Getting started
Visual Studio is an integrated development environment (IDE) in which C#, Visual Basic,
and C++ can be used as programming language to develop applications for the Windows
operating system. The word "integrated" refers to the fact that it contains a source code
editor, a compiler, tools for building a GUI application (see the glossary) and a debugger.
You can at this time minimise Visual Studio (click on ) and open Windows Explorer (press
-E) to inspect the folders and files that were created by Visual Studio.
Rename a form
Change the name of the form to something like "frmHelloWorld.cs" and press Enter.
Since the form is referenced in several places in the program, you will get a message to
confirm that you want to rename all occurrences of the name. Click OK.
You are free to choose any name for the form as long as the ".cs" extension is retained.
We have a convention (good habit) to use the first three characters of the name of an
object to indicate the class or type to which the object belongs, in this case "frm".
You have just developed your first C# program! It does not do much but at least you have a
running Windows application.
Note that there are two modes of a program, namely design mode where the program is
developed in the integrated development environment (IDE) of Visual Studio and run-time
mode where it is running like any other Windows application.
Chapter 1 5 Controls & Code
You can move the focus to the IDE while the program is running but you will not be able to
change anything. If the focus is on your application, you will have to press Alt-F4 or click
on to close it. If the focus is in Visual Studio, you can press Shift-F5 to close the
program.
A form is an object or "thing" in the same way that a motor car or a shoe or a person is an
object. Objects have properties that describe their appearance and behaviour. For example,
people have names and ID numbers, shoes have size and colour, cars have a make, model and
registration number.
Click anywhere on the form in design mode and locate the Properties window which is
normally docked at the right-hand side of the IDE. If you don't see it, click on View /
Properties Window.
Note that there are two lists, namely the properties ( ) and the events ( ). We will get
to events later. The properties can either be sorted alphabetically ( ) or alphabetically
within categories ( ). Note that some properties have brackets around them so that they
are listed at the top of the alphabetical list.
You can play around with the other properties. Change their values,
press F5 and inspect the effect. Look specifically at the effect of the
following: BackColor, ControlBox, Opacity, Size, StartPosition,
Text. Be careful not to set Opacity to 0%! You can also change the
value of the Size property by grabbing one of the form's handlers
with the mouse and dragging it.
Chapter 1 6 Controls & Code
You may close Visual Studio and switch off the computer at any time.
If you exit Visual Studio without saving, you will get a message which will ask you if you want
to save before exit. Click on Yes.
You can reopen your work at a time that is convenient for you.
If you want to open an earlier project that does not appear in the list of recent projects,
you will have to click on File / Open / Project /Solution … (or ) and then browse to the
".sln" file of your project. Click on OK.
Reference
http://msdn.microsoft.com/en-us/library/52f3sw5c.aspx
Chapter 1 7 Controls & Code
Locate the Toolbox window which is normally positioned on the left-hand side of the IDE.
If you don't see it, click on View / Toolbox.
Click on the next to the Common Controls group to open the list of common controls.
Change the button's Name property to btnMessage and its Text property to Message.
Position the button in the middle of the form.
Chapter 1 8 Controls & Code
Double click on the button. This will open a code window that will contain something
like the following:
Tabs
Braces
For the moment, you don't have to worry about what all this means. The most important
thing is that you realise that you have finally arrived in the world of C#. Until now, we
were only playing around in the graphical interface of Visual Studio, which is exactly the
same for other programming languages such as Visual Basic and Visual C++.
Things to note
Note the tabs at the top of the code window. You can always click on the frmHelloWorld.cs
[Design] tab to see the form design again. The asterisks in the tabs mean that the content
has been changed since the last save. Click on and see the asterisks disappear.
Curly braces, { and }, are used to box in certain fragments of the code. The braces occur
in pairs, meaning that there is a closing brace for every opening brace. The corresponding
opening and closing braces are vertically aligned. Braces that are not properly paired are
one of the most common errors that beginner programmers encounter.
Note the indents of the various program blocks. The indents are ignored by the compiler
but assist the human eye to identify how the programming parts fit into one another. In
the figure above, the programming parts are boxed with rectangles to show how they fit
entirely into one another like a series of baskets of different sizes.
Chapter 1 9 Controls & Code
Type the following line of code at the position of the arrow. Type the text exactly as
shown. Pay particular attention to the capitals and semicolon.
- Actually, the text between double quotes is a character string and is not recognised by
the compiler as belonging to the C# language. You can type any message there.
MessageBox.Show("Hello World!");
Click on the Message button. You have just executed your first line of C# code!
Things to know
Objects belong to classes. We can place many buttons on a form with each one of them
belonging to the class Button in the same way that all individual cars is a car and all
individual persons is a human. Of course, there are sub-classes and sub-sub-classes such
as all students being human and all full-time students being students. We can think of
objects and classes as things or members of a certain type or kind.
In object oriented terminology, we refer to the individual members of a class as instances.
When an object of a specific class is created we say that the object is instantiated. For
example, each time that a button is dragged from the toolbox to the form a new instance
of the class Button is instantiated. In other words, in general terms a specific button is an
object but it is specifically an instance of the class Button.
We have mentioned before that objects have properties that describe their appearance
and behaviour. The button in the example above has a Name property that is used to refer
to it in the code. It also has a Text property that is displayed to the user during run-time.
In this example Name is "btnMessage" and Text is "Message".
Objects can also experience events. In the example above, the button can be clicked in
which case a Click event is triggered.
There are many possible events for objects. Select the button in design mode and click on
in the Properties window to list its events. You will see that the Click event is
connected to an event handler, btnMessage_Click().
Chapter 1 10 Controls & Code
An event handler is a piece of code that will be executed when an event occurs, for
example the user clicking on a button. The following piece of code defines the event
handler for the Click event of the button:
This code says that a message box will be showed with the message "Hello World!" when
the button is clicked. Read this line of code as "Message box dot Show Hello World".
The first line of code as well as the curly braces was generated by Visual Studio when you
double clicked the button. You will later understand all the parts in the first line of code,
but for the moment it would suffice to point out that Visual Studio named the event handler
by combining the button's Name ("btnMessage") and the event (Click) with an underscore.
An event handler is also a method. Methods are pieces of C# code that describe the
actions done by objects. Methods are defined in the classes to which objects belong.
Methods have a header and a body. The header consists of several parts, inter alia the
name of the method. The header of the method always has brackets (not curly braces) at
the end. Sometimes there is something between the brackets, but sometimes there is
nothing between the brackets.
It is important to understand that all event handlers are methods, but not all methods are
event handlers. Event handlers are executed when an event occurs while other methods
are executed only when they are specifically called. The code in the listing above has two
methods, namely frmHelloWorld() and btnMessage_Click(), but only one of them,
btnMessage_Click(), is an event handler.
Individual lines of code within a method are called statements. Statements are always
followed by a semicolon as in the example below:
MessageBox.Show("Hello World!");
In the example above MessageBox is a class. This class and all its methods, inter alia
Show(), are defined in the .NET framework. This means that we do not have access to the
details of the class or the methods, but we are welcome to use it. You can inspect the
available methods for the MessageBox class by erasing the period and everything following
it. If you now type the period, a list of available methods will appear. We refer to this
feature of Visual Studio as IntelliSense.
Methods may or may not take parameters, i.e. values between the brackets, separated by
commas. Parameters are used during execution and provide information to the method
about the job that it must do.
Chapter 1 11 Controls & Code
If you type the method followed by an opening bracket a yellow box will appear to indicate
what possible parameters may be added. There are 21 possible combinations of
parameters for the MessageBox.Show() method. Press the up and down arrows to step
through the possibilities.
The first possible combination of parameters takes a single string value that will be
displayed when the message box is displayed. The third possibility takes two string
parameters – one for the message to be displayed and one for the text to be displayed in
the caption bar of the message box. Compare the following two statements with each
other:
Note that string parameters are entered between double quotes and numeric parameters
without quotes.
Browse to the folder where you want to save the project and ensure that the correct folder
is in the Location box.
Rename the file "Form1.cs" to "frmLogin.cs". The procedure was explained in the previous
chapter.
Open the Containers group in the Toolbox and drag a GroupBox to the form.
Set the Text property of the group box to an empty string. In other words, delete the
current value of the Text property.
Change the Name property of the button to "btnClose" and the Text property to "&Close".
Double click on the button and enter the following line of code in the Click() event
handler:
this.Close();
Run the program. See if you can find out what the effect is of the ampersand, "&", in the
Text property of the button.
Things to know
Group boxes, text boxes, labels, buttons, etc. are controls. Controls are also objects but
they are visible (graphical) "things" that we can add to a form.
The code in the button's Click() event handler refers to an object, this, and a method
Close(). The keyword, this, refers to the current instance of a class – in this case the
form. As always, a method does something on or with the relevant object. In this case the
current form will be closed when the user clicks on the Close button.
If you compare the button event handler above with the button event handler in the
previous example, it is import to note that this is an object while MessageBox is a class.
When a method is called with a class as in MessageBox.Show(), the method is referred to
as a static method. In other words, it is not necessary to instantiate an object in order to
call a static method.
Chapter 1 13 Controls & Code
Drag two labels, two text boxes and picture box to the form. Drag another button to the
group box.
Set the labels' Name properties to "lblName" and "lblPassword" and their Text properties
to "Name" and "Password".
Set the Name properties of the text boxes to "txtName" and "txtPassword" and ensure
that the Text properties are empty.
Set the PasswordChar property of txtPassword to "*".
Set the Name of the second button to "btnLogin" and its Text property to "&Log in".
Use the guidelines in design mode to align all controls properly. See the screen print below
for an example of the alignment of the Greeting button. Neat form layout is extremely
important. It creates positive first impressions of a program and is conducive to usability.
Select the Local resource radio button in the subsequent dialog box and click on
yourself, and click on and then on . (Hint: If you don't have a picture
of yourself, there are some scenes of nature on "C:\Documents and Settings\All Users\
Documents\My Pictures\Sample Pictures".)
Chapter 1 14 Controls & Code
Play around with the SizeMode property of the picture box and examine its effect.
Close the form again and enter the following line of code in the Click() event handler of
the Log in button:
Run the program again (F5). Enter your name in the text box and click on the Greeting
button. Watch the effect if you enter other names.
Set the TabIndex property of the text box to 0. Try to figure out what the effect of this is.
Set the AcceptButton property of the form to "btnLogin". Try to figure out what the
effect of this is.
Chapter 1 15 Controls & Code
Things to know
Instances of the class TextBox allow a user to enter character strings during run-time.
While the text box in the form, txtName, can accept any input, the label suggests to the
user that he/she must enter his/her name in the box. The value typed into the text box
during runtime is assigned to its Text property.
Instances of the class, Label, are used to provide information or instructions to a user.
The user cannot enter the text during runtime.
The line of code in the event handler of the Greeting button contains txtName.Text. This
time we have the object followed by a property. The Text property that is referred to in
the code is the exact same property that can be accessed through the Properties window
during design time. It is easy to distinguish properties from methods in the code since
methods are always followed by brackets and properties not.
The first parameter of the Show() method consists of three separate character strings that
are concatenated by the "+" operator. This means that the resulting string is a head-to-tail
composition of the three separate parts. The parts within quotes are used as they are,
while the value (contents of the box) of the txtName.Text property is used. Thus, if the
user enters "John" into the text box, the effective code becomes:
Naming conventions
A control should be given a name that will reflect the purpose thereof. Compare the
following two pieces of code and decide which version will be the easiest to maintain. This
issue becomes more and more important as the project becomes bigger and bigger with
more than one form and many labels, text boxes, buttons, etc.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
namespace Login
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
It is a good habit to name controls in such a way that the first three letters indicate to what
class the control belongs. Some of the most common control classes with the appropriate
prefixes are listed below:
Comments
Comments may be added to C# code in order to make notes for yourself or others who will
have to maintain your code. Comments are ignored by the compiler and have no effect on
program execution. Comments can, therefore, be considered as internal documentation of
what the program statements are doing.
Inline comments are indicated with two forward slashes //. Everything following the // on
the same line is ignored by the compiler
A multiline comment starts with /* and ends with */. Multiline comments can span several
lines and everything between /* and */ will be ignored by the compiler.
Every form (and later every class) in a project should include a comment block at the top
that indicates the programmer, date and scenario.
Chapter 1 17 Controls & Code
Things to do
Ensure that the code of your projects is well documented with comments
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 Login
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
Develop a Windows application that will display a traffic light as in the screen print below.
Chapter 1 18 Controls & Code
Close button
Add a Close button to the form and set the required properties as for the examples above.
Enter the appropriate code for the Click() event handler.
Form
Set the form's Text property to an empty string.
Set the ControlBox property to False.
Set the FormBorderStyle property to FixedSingle.
Set the StartPosition property to CenterScreen.
Picture boxes
Put three picture boxes on the form and name them "picRed", "picYellow" and
"picGreen" respectively.
Study the code above and then enter the appropriate code for the Click() event handlers
for the other two buttons.
Things to understand
The three picture box objects are initially all invisible.
When a button is clicked, one of the picture boxes is set to be visible while the others are
set to be invisible.
The code
picRed.Visible = true;
picYellow.Visible = false;
picGreen.Visible = false;
can be replaced with
picRed.Show();
picYellow.Hide();
picGreen.Hide();
with the same effect. The first set of lines sets the value of properties while the second set
calls methods of the PictureBox class that sets the Visible property. Note specifically
that properties do not have brackets while methods always have.
Chapter 1 19 Controls & Code
Resources
http://msdn.microsoft.com/en-us/beginner/bb308730.aspx
Keywords
You should make sure that you know what each of these items mean or where they are used.
Concepts : Normal
Files and folders : Normal between quotes, e.g. "frmLogin.cs".
Classes and Controls : Green, e.g. Color, PictureBox
Properties : Bold, e.g. Name
Property values : As it appears in code, e.g. "John", 10, CenterScreen.
Methods : Bold with brackets, e.g. Show()
Events : Bold with the word "event", e.g. Click event
Event handlers : As for methods, e.g. Close().
Reserved words : Blue, e.g. this
Chapter 1 20 Controls & Code
Exercises
1. Create a Windows Forms application to allow a user to enter his/her title, name and
surname. Add labels, text boxes, buttons and a combo box as in the example. When
the user clicks on the Greeting button, a message should be displayed that will
concatenate the user entries in the three fields and display a greeting.
Hint: Use the Items collection in the Properties window of the combo box to enter the
possible titles. During run-time, you can obtain the user's selection from the Text
property as for the text boxes.
2. Create a Windows Forms application that will allow the user to select a sports code from
a set of radio buttons. When the user clicks the button, an appropriate message and
picture must be displayed. You may be creative with the messages. See if you can find
out what the difference is between the default event for a radio button,
CheckedChanged, and the Click event.
Hint: There are some example pictures available on the CD that accompanies this
tutorial. Copy these into the "\bin\Debug" folder of your application and use the
ImageLocation property to load them into the picture box, for example:
picSport.ImageLocation = "Cricket.jpg";
Chapter 1 21 Controls & Code
3. Consider the following scenario: You have been asked to develop a program that can
be used by a lecturer to obtain statistics on the students in his class. Develop an
application with a form as in the example and characteristics as below: