be sharp with c# (chapter 1, controls and code)

21
Chapter One 1 Controls and Code After this chapter you should be able to add controls to a form be able to write basic C# code understand the importance of curly braces and indents understand the basics of objects and classes know what properties are and how to assign properties to objects know what is an event and an event handler know what is a method know how to give names to objects know how to use comments and what their purpose is Key concepts Controls, Objects & Classes Code Events and event handlers Methods and properties Naming conventions Comments

Upload: pieter-blignaut

Post on 18-Nov-2014

613 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Be sharp with C# (Chapter 1, Controls and Code)

Chapter One

1Controls and Code

After this chapter you should

be able to add controls to a form

be able to write basic C# code

understand the importance of curly bracesand indents

understand the basics of objects and classes

know what properties are and how to assignproperties to objects

know what is an event and an event handler

know what is a method

know how to give names to objects

know how to use comments and what theirpurpose is

Key concepts

Controls, Objects & Classes

Code

Events and event handlers

Methods and properties

Naming conventions

Comments

Page 2: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 2 Controls & Code

Getting started

Start Visual Studio 2008 and create a new project

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.

Click on Start / Visual Studio 2008

Click on File / New / Project …

Click on Windows Forms Application.

Give the project an appropriate name (Complete the box Name).

Browse to the folder where you want to save the project. Click on and ensure

that the correct folder is in the Location box.

Check the box Create directory for solution

Click on OK.

Page 3: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 3 Controls & Code

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

Right-click on "Form1.cs" in the Solution Explorer window.

Click on Rename.

Page 4: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 4 Controls & Code

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".

Run the application

You have just developed your first C# program! It does not do much but at least you have a

running Windows application.

Press F5 or click on to run the program

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.

Page 5: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 5 Controls & Code

You can move the focus to the IDE while the program is running but you will not be able tochange 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 theprogram.

Change the form's properties

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.

The list of properties has two columns – one for the

name of the property and one for its value. The Name

property already has a value which Visual Studio

derived from the file name that we entered above.

The Name property is the most important property of

any object. Visual Studio provides default names to

objects but it is a very good habit to change the

name of an object to reflect its function.

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.

Page 6: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 6 Controls & Code

Save, Close and Reopen your work

You may close Visual Studio and switch off the computer at any time.

Click on File / Save All (Alternatively press Ctrl-Shift-S or click on )

Click on File / Exit (Alternatively press Alt-F4 or click on )

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.

Click on File / Recent Projects and select your project.

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

Page 7: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 7 Controls & Code

Write your first C# code

Add a button to the form

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.

Drag a Button object from the toolbox to the form.

Change the button's Name property to btnMessage and its Text property to Message.

Position the button in the middle of the form.

Page 8: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 8 Controls & Code

Write the code

Double click on the button. This will open a code window that will contain something

like the following:

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.

Tabs

Braces

Page 9: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 9 Controls & Code

Type the 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!");

Run the program (press F5 or click on ).

Click on the Message button. You have just executed your first line of C# code!

Click OK in the message box and close the program (click on ).

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().

Page 10: Be sharp with C# (Chapter 1, Controls and Code)

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:

private void btnMessage_Click(object sender, EventArgs e){

MessageBox.Show("Hello World!");}

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.

Page 11: Be sharp with C# (Chapter 1, Controls and Code)

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:

MessageBox.Show("Hello World!"); MessageBox.Show("Hello World!", "Message");

Note that string parameters are entered between double quotes and numeric parameterswithout quotes.

Close the project so that we can start with a new one:

Click on File / Close Solution.

Click on Yes to save if the last changes were not saved

Add controls from the toolbox

Let us start with a new project.

Design the form

Click File / New / Project …

Give a name to the project, "Login".

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.

Change the Text property of the form to "Login".

Open the Containers group in the Toolbox and drag a GroupBox to the form.

Set the Name property of the group box to "grpButtons".

Page 12: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 12 Controls & Code

Set the Text property of the group box to an empty string. In other words, delete the

current value of the Text property.

Set the Dock property of the group box to Bottom.

Run the program (press F5) and see what the effect is of the Dock property if you resize

the form during run-time. Close the form again (click ).

Drag a button to the group box.

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.

Click on the button. The form will close.

If the form closes correctly, you can set the ControlBox property of the form to False.

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.

Page 13: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 13 Controls & Code

Add the controls and enter the 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.

Set the Name of the picture box to "picPhoto".

Click on the next to the Image property of the picture box.

Select the Local resource radio button in the subsequent dialog box and click on

. Browse to any picture on your computer, for example a photograph of

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".)

Page 14: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 14 Controls & Code

Play around with the SizeMode property of the picture box and examine its effect.

Run the program and check that everything is working.

Close the form again and enter the following line of code in the Click() event handler of

the Log in button:

MessageBox.Show("Good day, " + txtName.Text + "!", "Log in");

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.

Page 15: Be sharp with C# (Chapter 1, Controls and Code)

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.

A picture box can be used to display a picture 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:

MessageBox.Show("Good day, John!", "Log in");

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();}

private void button1_Click(object sender, EventArgs e){

this.Close();}

private void button2_Click(object sender, EventArgs e){

MessageBox.Show("Good day, " + textBox1.Text + "!", "Greeting");}

}}

Page 16: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 16 Controls & Code

namespace Login{

public partial class frmLogin : Form{

public frmLogin(){

InitializeComponent();}

private void btnClose_Click(object sender, EventArgs e){

this.Close();}

private void btnGreeting_Click(object sender, EventArgs e){

MessageBox.Show("Good day, " + txtName.Text + "!", "Greeting");}

}}

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:

btn Button

cmb ComboBox

chk CheckBox

cld ColorDialog

dtp DateTimePicker

fod FontDialog

frm Form

grp GroupBox

img Image

lbl Label

lst ListBox

ofd OpenFileDialog

pic PictureBox

pnl Panel

prb ProgressBar

rad RadioButton

rtb RichTextBox

sfd SaveFileDialog

tbc TabControl

tmr Timer

txt TextBox

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.

Page 17: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 17 Controls & Code

Things to do

Ensure that the code of your projects is well documented with comments

/* Student number : 2010123456Student name : Pieter BlignautScenario : Demonstration of the use of labels, buttons and text

boxes on a form.Date : 16 November 2009

*/

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();}

//Event handler for the Close buttonprivate void btnClose_Click(object sender, EventArgs e){

this.Close(); //Close the form}

//Event handler for the Greeting buttonprivate void btnGreeting_Click(object sender, EventArgs e){

//Display greeting with the name of the userMessageBox.Show("Good day, " + txtName.Text + "!", "Greeting");

}}

}

Traffic light example

Develop a Windows application that will display a traffic light as in the screen print below.

Page 18: Be sharp with C# (Chapter 1, Controls and Code)

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.

Load the images "LightRed.jpg", "LightYellow.jpg" and "LightGreen.jpg" in the respective

picture boxes. You can find these files on the CD that accompanies this tutorial.

Make sure that the picture boxes are exactly the same size and that they are positioned

exactly on top of one another.

Set SizeMode property of the picture boxes Zoom.

Set the Visible property of all picture boxes to False.

Traffic light buttons

Add the Red, Yellow and Green buttons as in the screen print.

Set the buttons' Text properties as in the screen print.

Set the buttons' Name properties to btnRed, btnYellow and btnGreen respectively.

Enter the following code for the Click() event handler of the Red button:

picRed.Visible = true;picYellow.Visible = false;picGreen.Visible = false;

Study the code above and then enter the appropriate code for the Click() event handlers

for the other two buttons.

Run the program and click on the buttons in turn.

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.

Page 19: Be sharp with C# (Chapter 1, Controls and Code)

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.

.NET framework+ OperatorAcceptButton

AmpersandApplicationBackColor

BraceBracketButton

ClassClick eventClose()

Code windowCommentConcatenateControlControlBox

ConventionDesign modeDirectoryDock

Double quoteDragEventEvent handlerFileFolderFormForm handlerForm layoutFormBorderStyle

Graphical interface

GroupBoxHide()

IDEImage

IndentInline commentInstanceInstantiateIntelliSenseLabelMessageBox

MethodMinimiseMultiline commentsName

Naming conventionNumeric valuesObjectOpacity

ParameterPictureBox

ProjectPropertyRun-timeSaveShow()

Single quotesSizeSizeMode

Solution ExplorerStartPosition

Statement

Static methodString valueSub-classTabTabIndexTextTextBoxthis

ToolboxUsabilityVisible

Visual StudioWidth

Windows ExplorerWindows Forms application

Short cuts

-EAlt-F4Ctrl-Shift-SF5Shift-F5

Icons and Buttons

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

Page 20: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 20 Controls & Code

Exercises

1. Create a Windows Forms application to allow a user to enter his/her title, name andsurname. Add labels, text boxes, buttons and a combo box as in the example. Whenthe user clicks on the Greeting button, a message should be displayed that willconcatenate 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 Textproperty as for the text boxes.

2. Create a Windows Forms application that will allow the user to select a sports code froma set of radio buttons. When the user clicks the button, an appropriate message andpicture must be displayed. You may be creative with the messages. See if you can findout 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 thistutorial. Copy these into the "\bin\Debug" folder of your application and use theImageLocation property to load them into the picture box, for example:

picSport.ImageLocation = "Cricket.jpg";

Page 21: Be sharp with C# (Chapter 1, Controls and Code)

Chapter 1 21 Controls & Code

3. Consider the following scenario: You have been asked to develop a program that canbe used by a lecturer to obtain statistics on the students in his class. Develop anapplication with a form as in the example and characteristics as below:

Solution saved as : Ch01Ex03.sln

Form- Saved as : frmNameSurname.cs- Caption : Name and Surname- Height & Width : 235 & 467- Starting position in the middle of the screen- Cannot be resized during run-time- Cannot be minimised or maximised during run-time

Controls:- Labels and text boxes for name and surname- Label and date/time box for date of birth- Label and combo box for degree.

- Available items: B.Sc., B.Com., B.A., B.Th., B.Ed., Other.- Items in the box must always be sorted alphabetically.

- Group with radio buttons as in the example. A student can study for only one degreeat a time.

- Group with check boxes as in the example. A student may have subjects from morethan one year and must therefore be able to select more than one box.

- Button to clear all contents with shortcut as indicated- Button to exit application with shortcut as indicated- All controls must be properly named- All controls must be properly aligned and spaced- The user should be able to move focus from one control to the other in a logical

order with Tab/Shift-Tab.

Code- For Clear button- For Exit button

Comment- Student number, name and date- Running comment to explain what the code is doing

4. Develop a simple form as in the example. When the userclicks on the button, the form's background colour mustchange to light blue and the button must change to Grey.When the user clicks the Grey button, the form's backgroundcolour must change back to grey and the button to Light blue.Hint: To obtain a colour, type the class Color followed by a

period and use IntelliSense to select a colour.