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

Share Embed Donate


Short Description

Download Be sharp with C# (Chapter 1, Controls and Code)...

Description

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

Chapter 1

2

Controls & Code

Getting started Start Visual Studio 2008 and create a new project integrate ated d develo developme pment nt environ environmen mentt (IDE) (IDE) in which which C#, Visual Visual Bas Basic, ic, Visual Studio is an integr 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 wse to the folde lder where here you want to save the pro projec ject. Clic Click k on that the correct folder is in the Location box. Check the box Create directory for solution solution Click on OK.

and ensure

Chapter 1

3

You can at this time minimise Visual Studio (click on

Controls & Code

) and open Windows Explorer (press

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

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 confirm that you want to rename all occurrences occurrences of the name. name. Click OK.

You are free to choose any name for the form as long as the ".cs" extension is retained. We have have a conv conven entio tion n (goo (good d habit habit)) to use use the first first three three charac character ters s of the the name name of an object to indicate the class or type to which the object belongs, in this case "frm".

Run the application You have have just developed developed your first first C# progra program! m! It does not do much much but at least least you have a running Windows application. Press F5 or clic click k on

to run run the the prog progra ram m

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 change anything anything.. If the focus is on your your applic applicatio ation, n, you will have to press press Alt-F4 or click on to clo clos se it. it. program.

If the the foc focus is is in Vis Visua uall St Stud udio io,, you you can can pre press ss Shift-F5 to clos close e the the

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. object. Objects Objects have properties that describe describe their appearance appearance and behaviour. behaviour. For example, example, people have names and ID numbers, shoes have size and colour, cars have a make, model and registration number. Clic Click k anyw anywhe here re on the the form form in desi design gn mode mode and and loc locat ate e the the Properties window window which which is norm normal ally ly dock docked ed at the the right right-h -han and d side side of the the IDE. IDE. If you don't don't see see it, it, clic click k on View / Properties Window. Note Note tha thatt ther there e are are two two list lists, s, name namely ly the the pro proper pertie ties s (

) and and the the eve event nts s (

to event events s late later. r. The The proper propertie ties s can either either be sort sorted ed alpha alphabe beti tica cally lly ( within within categ categori ories es (

). We will will get get

) or alph alphab abet etic ical ally ly

). Note Note that some some prope propertie rties s have brac bracket kets s around around them them so that that they 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 prope propert rty y alre alread ady y has has a value value whic which h Visua Visuall Stud Studio io deriv derived ed from from the the file file name name that that we ente entere red d above above.. The Name property is the most important property of  any object. object. Visual Visual Studio Studio provides provides default default names names to obje object cts s but but it is a very very good good habi habitt to chan change ge the the name of an object to reflect its function.

You can play around around with with the other other propert properties ies.. Change Change their their values values,, press F5 and inspect the effect. Look specifically at the effect of the following: BackColor, ControlBox , Opacity, Size, StartPosition , Text. Be car caref eful ul not not to set set Opacity to 0%! You can also change the value value of the the Size proper property ty by grabb grabbing ing one one of the the form' form's s handl handler ers s with the mouse and dragging it.

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 save before before exit. exit. Click 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 ".sln" ".sln" file of your project project.. Click Click on OK.

Reference http://msdn.microsoft.com/en-us/library/52f3sw5c.aspx

) and then browse wse to the

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. Clic lick on the the

nex next to the the Common Controls group to open the list of common controls.

Drag a Button object from the toolbox to the form. Change Change the button' button's s Name propert property y to btnMessage and and its its Text propert property y to Message. Position the button in the middle of the form.

Chapter 1

8

Controls & Code

Write the code Double Double click click on the button button.. This This will will open open a code code window window that will contain contain somethin something g like the following: Tabs

Braces

For the moment, moment, you don't have to worry worry about what all this means. means. The most most import important ant thing thing is that that you real realis ise e that that you have have finally finally arriv arrived ed in the the world world of C#. C#. Unti Untill now, now, we were were only playing playing around around in the graphic graphical al interf interface ace of Visual Visual Studio Studio,, which which is exactl exactly y 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. window. You You can always 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 change changed d since since the last last save save.. Click Click on on and see the asteri asterisks sks disappe disappear. ar. Curly braces, braces , { and }, are used to box in certai certain n fragment fragments s of the code. code. The braces braces occur occur in pairs, pairs, meaning meaning that there is a clo closin sing g brace brace for every every opening opening brace. brace. The correspo correspondin nding g opening opening and clo closin sing g braces braces are vertic verticall ally y aligne aligned. d. Braces Braces that are not properly properly paired paired are one of the most common errors that beginner programmers encounter. Note the indents of the variou various s program program blocks blocks.. The indents indents are ignored ignored by the compil compiler er but assist assist the human eye to identif identify y how the programm programming ing parts parts fit into into one another another.. In the figure above, above, the programmi programming ng parts parts are boxed with rectangle rectangles s to show show how they they fit entirely into one another like a series of baskets of different sizes.

Chapter 1

9

Controls & Code

Type the code Type Type the the foll follow owin ing g line line of code code at the the posi positi tion on of the the arro arrow. w. Type Type the the text text exac exactl tly y as shown. shown. Pay particular particular attention attention to the capitals and semicolon. semicolon. - Actual Actually, ly, the text text between between double quotes quotes is a charac character ter string string and is not recognis recognised ed by the compiler compiler as belonging belonging to the C# language. language. You can type any message message there.  MessageBox.Show(  MessageBox .Show("Hel "Hello lo Worl World!" d!"); );

Run the program (press F5 or click ick on

).

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

Click OK in the the mes messa sage ge box box and and clo close se the progr program am (cl (clic ick k on

).

Things to know Objects belong to classes. classes. We can place place many many button buttons s on a form form with each each one of them belongin belonging g to the class class Button in the the same same way way that that all all indi indivi vidu dual al cars cars is a car car and and all all individual individual persons is a human. Of course, there are sub-classes sub-classes and sub-sub-clas sub-sub-classes ses such as all all stude students nts being being huma human n and and all all fullfull-ti time me stude student nts s being being stude student nts. s. We can can think 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. instances. When an object of a specific class is created we say that the object is instantiated. instantiated. For example, each time that a button is dragged from the toolbox to the form a new instance of the class Button is instantiate instantiated. d. In other words, words, in general terms a specific specific button is an object but it is specifically an instance of the class Button . We have have mentio mentioned ned before before that that object objects s have have properties that describe their appearance and behavi behaviour our.. The button button in the example example above above has a Name property that is used to refer to it in the cod code. e. It also also has has a Text property that is displayed to the user during run-time. In this example Name is " btnMessage" and Text is " Message". Objects Objects can also experience experience events. events. In the example above, the button can be clicked in which case a Click event is triggered. There There are many many possibl possible e events for objects. objects. Select Select the button in design design mode and click on in the the Properties wind window ow to list list its even events ts.. You You will will see that that the the Click even eventt is connected to an event handler, btnMessage_Click().

Chapter 1

10

Controls & Code

An event event handler handler is a piec piece e of code code that that will will be exec execut uted ed when when an even eventt occu occurs rs,, for for exam example ple the user user clic clicki king ng on a butt button on.. The The follo followi wing ng piece piece of code code define defines s the the even eventt handler for the Click event of the button:   private private void btnMessage_Click( object sender, EventArgs e) {  MessageBox.Show(  MessageBox .Show("Hel "Hello lo Worl World!" d!"); ); }

This code says that a message box will be showed with the message "Hello World!" when the button is clicked. clicked. Read this line of code as "Message "Message box dot Show Hello World". World". The first line of code as well as the curly braces was generated by Visual Studio when you double double clicked clicked the button. button. You will later later underst understand and all the parts parts in the first 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 even eventt hand handle lerr is also also a method. method. Me Meth thod ods s are are piec pieces es of C# code code that that descr describ ibe e the the actions actions done by objects. objects. Methods Methods are defined in the classes classes to which objects belong. Methods have a header and a body. body. The header header consis consists ts of several several parts, parts, inter alia the name name of the method. method. The header header of the method method always always has brackets brackets (not curly curly braces) braces) at the end. end. So Some metim times es there there is some someth thing ing betw betwee een n the brac bracke kets ts,, but some sometim times es there there is nothing between the brackets. It is important to understand that all event handlers are methods, but not all methods are event event handle handlers. rs. Event Event handlers handlers are execut executed ed when when an event occurs occurs while while other methods methods are execute executed d only only when when they they are specific specificall ally y calle called. d. The code in the listing listing above above has two Click(), but only one of them, methods, methods, namely namely frmHelloWorld() and btnMessage _ Click()  btnMessage _ Click() Click(), is an event handler. Individ Individual ual lines of code within within a method method are called called statemen statements. ts. followed by a semicolon as in the example below:

Stateme Statements nts are always always

 MessageBox.Show(  MessageBox .Show("Hel "Hello lo Worl World!" d!"); );

inter alia alia In the example example above MessageBox is a clas class. s. This This clas class s and and all all its its meth method ods, s, inter defined in the .NET framew framework ork.. This means means that we do not have have access access to the Show(), are defined deta detail ils s of the class class or the the meth methods ods,, but but we are welc welcom ome e to use it. You You can can inspe inspect ct the available methods for the MessageBox class by erasing the period and everything following it. If you now type type the the period period,, a list of avail availab able le metho methods ds will will appe appear ar.. We refer refer to this this feature of Visual Studio as IntelliSense.

Methods may or may not take parameters, parameters, i.e. values between the brackets, separated by commas commas.. Parame Parameter ters s are used during executi execution on and provide provide informa informatio tion n to the method 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 what pos possible ible para param mete eters may be adde added. d. There here are are 21 poss possib ible le comb combin ina ation tions s of  MessageBox.Show() .Show() meth parame parameters ters for the MessageBox method od.. Press Press the the up and and down down arro arrows ws to step step through the possibilities.

The The firs firstt possi possibl ble e combi combina nati tion on of param paramete eters rs take takes s a sing single le string valu value e that that will will be displ display ayed ed when when the the mess messag age e box is displa displaye yed. d. The The third third poss possib ibil ilit ity y take takes s two two strin string g parameters – one for the message to be displayed and one for the text to be displayed in the captio caption n bar bar of the mess messag age e box. box. Compa Compare re the the follo followi wing ng two two stat statem emen ents ts with with each each other:  MessageBox.Show(  MessageBox .Show("Hel "Hello lo Worl World!" d!"); );

MessageBox.Show( MessageBox .Show("Hel "Hello lo Worl World!" d!", , "Message" "Message"); );

Note that string parameters are entered between double quotes and numeric parameters without 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 Rename the file "Form1.cs" "Form1.cs" to "frmLogin.c "frmLogin.cs". s". The procedure was explained 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".

Chapter 1

12

Controls & Code

Set the Text prop proper erty ty of the the group group box box to an empt empty y stri string. ng. In other other words words,, delet delete e the the current value of the Text property. Set the Dock property of the group box to Bottom . Run the program (press F5) F5) and see what the effect is of the Dock property if you resize the form form during during runrun-ti time me.. Close Close the the for form m aga again in (clic (click k

).

Drag a button to the group box. Change the Name property of the button to "btnClose" and the Text property to "&Close" .

Doub Double le clic click k on the the butt button on and and ente enterr the the foll follow owin ing g line line of code code in the the Click() event handler: this.Close(); this .Close();

Run the program. program. See if you can find out what the effect effect is of the ampersand ampersand,, "&", in the Text property of the button. Click Click on the button button.. The form form will close. close. If the form closes correctly, you can set the ControlBox property of the form to False.

Things to know Group Group boxes, boxes, text boxes, labels, labels, buttons, buttons, etc. are contro controls. ls. Contro Controls ls are also objects 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 The keyw keywor ord, d, this, refers to the current instance of a class – in this case the Close(). The form. form. As always, always, a method method does does something something on or with the relevant relevant object. object. In this case case the current form will be closed when the user clicks on the Close button. If you you comp compar are e the the butto button n even eventt handl handler er abov above e with with the the butto button n even eventt handl handler er in the the previous example, it is import to note that this is an object while MessageBox is a class. MessageBox.Show() .Show(), the method is referred to When a method is called with a class as in MessageBox as a static method method.. In other words, words, it is not necessa necessary ry to instan instantia tiate te an object object in order to call a static method.

Chapter 1

13

Controls & Code

Add the controls and enter the code Drag Drag two labels, labels, two text boxes boxes and picture picture box to the form. form. Drag Drag anothe anotherr button 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 propert properties ies of the text boxes boxes to "txtName" and "txtPassword" and ensure 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 "&L "&Log og in". Use the guidelines in design mode to align all controls controls properly. properly. See the screen print below for for an exam example ple of the alig alignm nmen entt of the Greeting butt button on.. Neat Neat form layout layout is extr extrem emely ely important. It creates positive first impressions of a program and is conducive to usability.

Set the Name of the picture box to "picPhoto". Clic Click k on the the

nex next to the the Image property of the picture box.

Sele Se lect ct the the Local radio o butt button on in the the subs ubseque equent nt dia dialog log box box and clic click k on Local resource resource radi . Brow Browse se to any any pict pictur ure e on your your comp comput uter er,, for for exam exampl ple e a phot photog ogra raph ph of  yourself, and click on

and then on

. (Hint: If you don't have a picture

of yourse yourself, lf, there there are some some scenes scenes of nature nature on "C:\Do "C:\Docum cument ents s and Setting Settings\ s\All All Users\  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. 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(  MessageBox .Show("G "Goo ood d da day, y, " + txt txtNam Name.T e.Text ext + "!" "!", , "Lo "Log g in" in"); );

Run the program again (F5 ( F5). ). Ente Enterr your your name name in the the text box and and clic click k on the Greeting button. Watch Watch the effect if you enter enter other names. names.

Set the TabIndex propert property y of the text box to 0. Try to figure figure out what the effect effect of this is. Set the Set the AcceptButton prope propert rty y of the form to "btnLogin" . effect of this is.

Try to figu figure re out out what what the the

Chapter 1

15

Controls & Code

Things to know Instan Instances ces of the class class TextBox allow allow a user user to enter enter charac character ter strings strings during run-tim run-time. e. While the text box in the form, txtName, can accept any input, the label suggests to the user user that he/sh he/she e must must enter enter his/h his/her er name in the the box. box. The The value value typed typed into the text text box during runtime is assigned to its Text property. Instan Instances ces of the class class,, Label, are used to provide provide informat information ion or instru instructi ctions ons to a user. 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 time we have have the the objec objectt foll follow owed ed by a prop propert erty. y. The The Text property that is referred to in the code is the exact same property that can be accessed through the Properties window during during design design time time.. It is easy easy to distin distingu guis ish h prope propert rtie ies s from from meth methods ods in the the code code sinc since e 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 concatenated by the "+" operator. This means that the resulting resulting string is a head-to-tail head-to-tail compo composi sitio tion n of the the thre three e sepa separa rate te parts parts.. The parts parts withi within n quote quotes s are are used used as they they are, are, while the value (contents of the box) of the txtName.Text prope propert rty y is used used.. Thus Thus,, if the the user enters "John" into the text box, the effective code becomes:  MessageBox.Show(  MessageBox .Show("Go "Good od day day, , Joh John! n!" " , "Lo "Log g in" in"); );

Naming conventions A cont control rol should should be give given n a name name that that will reflec reflectt the the purpos purpose e there thereof of.. Comp Compar are e the the follow following ing two piece pieces s of code and decide decide which version version will be the easies easiestt to maintain. maintain. This This issue issue become becomes s more and more more importa important nt as the project project become becomes s bigger bigger and bigger with with more than one form and many labels, text boxes, buttons, etc. namespace WindowsFormsApplication1 {   public public part partial ial clas class s Form1 : Form  {  public Form1() { InitializeComponent(); }   private private void button1_Click( object sender, EventArgs e) { this.Close(); this .Close(); }   private private void button2_Click( object sender, EventArgs e) {  MessageBox.Show(  MessageBox .Show("G "Goo ood d da day, y, " + tex textBo tBox1. x1.Tex Text t + "!" "!", , "Greeting" "Greeting"); ); } } }

Chapter 1

16

Controls & Code

namespace Login {   public public part partial ial clas class s frmLogin : Form  {  public frmLogin() { InitializeComponent(); }   private private void btnClose_Click( object sender, EventArgs e) { this.Close(); this .Close(); }   private private void btnGreeting_Click( object sender, EventArgs e) {  MessageBox.Show(  MessageBox .Show("G "Goo ood d da day, y, " + txt txtNam Name.T e.Text ext + "!" "!", , "Greeting" "Greeting"); ); } } }

It is a good habit to name controls in such a way that the first three letters indicate to what class class the contro controll belongs belongs.. Some Some of the most most common common control control class classes es with with the appropria appropriate te prefixes are listed below: btn cmb chk cld dtp fod frm grp img lbl lst

Button ComboBox CheckBox ColorDialog DateTimePicker FontDialog Form  GroupBox Image Label ListBox

ofd pic pnl prb rad rtb sfd tbc tmr txt

OpenFileDialog PictureBox Panel ProgressBar RadioButton RichTextBox SaveFileDialog TabControl Timer TextBox

Comments Comments may be added to C# code in order to make notes for yourself or others who will have have to maintain maintain your code. code. Comment Comments s are ignore ignored d by the compile compilerr and have have no effect effect on program program execution. Comments Comments can, therefore, therefore, be considered as internal documentatio documentation n of  what the program statements are doing. Everything hing foll followin owing g the //  on Inline comments are indicated with two forward slashes // . Everyt the same line is ignored by the compiler A multiline starts with /* and ends with */. Multili Multiline ne comments comments can can span span severa severall multiline comment starts 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 /* Stu Stude dent nt numbe number r Stu tude dent nt nam ame e Scenario Date

: 2010 201012 1234 3456 56 : Pi Piet eter er Bli lign gnau aut t : De Demonstration of of th the us use of of la labels, bu buttons an and te text   box boxes es on a fo form rm. . : 16 November 2009

*/ using using using using using using using using

System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms;

namespace Login {   public public part partial ial clas class s frmLogin : Form  {  public frmLogin() { InitializeComponent(); } //Even //E vent t han handle dler r for the Clo Close se but button ton   private private void btnClose_Click( object sender, EventArgs e) { this.Close(); this .Close(); //C //Clos lose e the for form  m  } //Event //Even t han handle dler r for the Gre Greeti eting ng but button ton   private private void btnGreeting_Click( object sender, EventArgs e) { //Di // Disp spla lay y gr gree eeti ting ng wi with th th the e na name me of th the e us user er  MessageBox.Show(  MessageBox .Show("G "Goo ood d da day, y, " + txt txtNam Name.T e.Text ext + "!" "!", , "Greeting" "Greeting"); ); } } }

Traffic light example 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 Putt thre Pu three e pic picture ture boxe boxes s on the the form form and nam name them them "picRed", "picYellow" and "picGreen" respectively. Load the images "LightRed.jpg" "LightRed.jpg",, "LightYellow. "LightYellow.jpg" jpg" and "LightGreen. "LightGreen.jpg" jpg" in the respective respective picture boxes. boxes. You can find these files on the CD that accompanie accompanies s 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, 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. picRed.Visi Visible ble = true true; ;   picYellow.Visible picYellow.Visible = false false; ;   picGreen.V picGreen.Visible isible = false 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. picRed.Visi Visible ble = true true; ;   picYellow.Visible picYellow.Visible = false false; ;   picGreen.V picGreen.Visible isible = false false; ;

can be replaced with  picRed.Show();  picYellow.Hide();  picGreen.Hide();

with the same effect. effect. The first first set set of lines sets the value of proper properties ties while while the second second set calls methods of the PictureBox class that sets the Visible propert property. y. Note Note specific specifical ally ly 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.

.NET framework + Operator

GroupBox Hide()

 AcceptButton

IDE

Ampersand Application

Image

BackColor

Brace Bracket Button

Class Click event Close()

Code window Comment Concatenate Control ControlBox

Convention Design Design mode Directory

Indent Inline comment Instance Instantiate IntelliSense Label  MessageBox

Method Minimise Multiline comments  Name

Naming convention Numeric values Object Opacity

Parameter

Dock

PictureBox

Double quote Drag Event Event handler File Folder Form Form handler Form layout

Project Property Run-time Save

FormBorderStyle

Graphical interface

Concepts Files Files and and folde folders rs Class Classes es and Contr Controls ols Properties Prope ropert rty y valu values es Methods Events Event handle ndlerrs Reserved words

Show()

Static method String value Sub-class Tab TabIndex Text TextBox this

Toolbox Usability  Visible

Visual Studio  Width

Windows Explorer Windows Forms application

Short cuts -E Alt-F4 Ctrl-Shift-S F5 Shift-F5

Icons and Buttons

Single quotes quotes Size SizeMode

Solution Explorer StartPosition

Statement

: Normal : Norm Normal al betw betwee een n quotes quotes,, e.g. e.g. "frm "frmLo Login gin.c .cs" s".. : Green, Green, e.g. e.g. Color, PictureBox : Bold, e.g. Name : As it appe ppears ars in code code,, e.g. e.g. "John", 10, CenterScreen. : Bold with brackets, e.g. Show() : Bold with the word "event", e.g. Click event : As for methods, ds, e.g. Close(). : Blue lue, e.g. this

Chapter 1

20

Controls & Code

Exercises 1.

Crea Create te a Wind Window ows s Forms Forms appl applic icat atio ion n to allo allow w a user user to ente enterr his/h his/her er titl title, e, name name and and surnam surname. e. Add labels labels,, text boxes, boxes, button buttons s and a combo combo box as in the exampl example. e. When When the the user user clic licks on the the Greeting butt button on,, a mess messag age e shou should ld be disp displa laye yed d that that will 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 poss possibl ible e titl titles es.. Duri During ng runrun-ti time me,, you you can can obta obtain in the user user's 's selec selectio tion n from from the the Text Text property as for the text boxes.

2.

Create Create a Windo Windows ws Form Forms s applic applicati ation on that that will will allow allow the user user to select select a sport sports s co code de from from a set of radio buttons buttons.. When When the user user clicks clicks the button, button, an appropr appropriat iate e message message and pictur picture e must be displa displayed yed.. You You may be creativ creative e with the messa messages ges.. See if you can find out what the difference is between the default event for a radio button, CheckedChanged , and the Click event. Hint Hint:: Ther There e are are some some exam example ple pictu picture res s avai availa lable ble on the CD that that acco accomp mpan anies ies this this tuto tutoria rial. l. Copy Copy thes these e into into the the "\bin "\bin\D \Deb ebug" ug" folder folder of your your appli applica cati tion on and and use use the the ImageLocation property to load them into the picture box, for example:   picSport.I picSport.ImageLocatio mageLocation n = "Cricket.jpg"; "Cricket.jpg";

Chapter 1

3.

21

Controls & Code

Cons Conside iderr the the follo followi wing ng sce scenar nario io:: You You have have bee been n as aske ked d to dev devel elop op a pro progra gram m that that can can be used by a lect lectur urer er to obtain obtain stat statis isti tics cs on the the stude student nts s in his clas class. s. Deve Develo lop p an application with a form as in the example and characteristics as below:

Solut So lutio ion n save saved d as

: Ch01E Ch01Ex0 x03. 3.sl sln n

Form - Sav Saved as : frmNameSurname.cs - Caption : Name and Surname - Heig Height ht & Wid Width th : 235 235 & 467 467 - Starti Starting ng positio position n in the middle middle of the scree screen n - Cannot Cannot be be resized resized durin during g run-tim run-time e - Cannot be minimised minimised or or maximised maximised during during run-time run-time Controls: - Labels Labels and and text text boxes for for name name and surnam surname e - Label Label and date/ date/time time box box for date date of birth birth - Label Label and and combo combo box for degre degree. e. - Available Available items: items: B.Sc., B.Sc., B.Com., B.Com., B.A., B.Th., B.Th., B.Ed., B.Ed., Other. - Items Items in the box must must always always be sorted sorted alphabeti alphabetica cally lly.. - Group Group with radio radio button buttons s as in the example example.. A student student can study study for only only one degree degree at a time. - Group Group with check check boxes boxes as in the example. example. A student student may have have subjects subjects from from more than one year and must therefore be able to select more than one box. - Button to clear all content contents s with shortcut shortcut as as indicated indicated - Button to exit exit applicatio application n with shortcut shortcut as as indicated indicated - All contr controls ols must must be proper properly ly named named - All contro controls ls must be properl properly y aligned aligned and spaced spaced - The user user should should be able to move focus focus from one contro controll to the other in a logical logical order with Tab/Shift-Tab . Code - For Clear button - For Exit button Comment - Studen Studentt number number,, na name me and and date date - Running Running comme comment nt to explain explain what what the code code is doing 4.

Develo velop p a sim simp ple form form as as in in the the examp xample le.. When hen the the user user clic clicks ks on the the butto button, n, the form form's 's back backgro ground und colou colourr must must chan change ge to light light blue blue and and the button button must must chan change ge to Grey. When the user clicks the Grey button, the form's background colour 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.

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF