1
1
Controls and Code
Controls and Code
After this chapter you should
After this chapter you should
be able to add controls to a form
be able to add controls to a form
be able to write basic C# code
be able to write basic C# code
understand the importance of curly braces
understand the importance of curly braces
and indents
and indents
understand the basics of objects and classes
understand the basics of objects and classes
know what properties are and how to assign
know what properties are and how to assign
properties to objects
properties to objects
know what is an event and an event handler
know what is an event and an event handler
know what is a method
know what is a method
know how to give names to objects
know how to give names to objects
know how to use comments and what their
know how to use comments and what their
purpose is
purpose is
Key concepts
Key concepts
Controls, Objects & Classes
Controls, Objects & Classes
Code
Code
Events and event handlers
Events and event handlers
Methods and properties
Methods and properties
Naming conventions
Naming conventions
Comments
Getting started
Getting started
Start Visual Studio 2008 and create a new project
Start Visual Studio 2008 and create a new project
Visual Studio
Visual Studio is is an an intintegregrateated d devdeveloelopmepment nt envenvironironmenment t (ID(IDE) E) in in whiwhich ch C#, C#, VisVisual ual BasBasic,ic, and C++ can be used as programming language to develop applications for the Windows 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 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. editor, a compiler, tools for building a GUI application (see the glossary) and a debugger. Click on
Click on Start / Visual Studio 2008Start / Visual Studio 2008
Click on
Click on File / New / Project …File / New / Project …
Click on
Click on Windows Forms ApplicationWindows Forms Application..
Give the project an appropriate name (Complete the box
Give the project an appropriate name (Complete the box NameName).). B
Brroowswse e tto o tthhe e ffooldldeer r wwhehere re yyoou u wwaannt t tto o ssaave ve tthe he prproojejecctt. . ClClicick k oon n aannd d eennssuurere that the correct folder is in the
that the correct folder is in the LocationLocation box.box. Check the box
Check the box Create directory for Create directory for solutiosolutionn Click on
You can at this time minimise
You can at this time minimise Visual StudioVisual Studio ((cclliicck k oon n ) ) aannd d ooppeenn Windows ExplorerWindows Explorer (press(press -E
-E) to inspect the folders and files that were created by Visual Studio.) to inspect the folders and files that were created by Visual Studio.
Rename a form
Rename a form
Right-click on "Form1.cs" in the
Right-click on "Form1.cs" in the Solution ExplorerSolution Explorer window.window. Click on
Change the name of the form to something like "frmHelloWorld.cs" and press
Change the name of the form to something like "frmHelloWorld.cs" and press EnterEnter..
Since the form is referenced in several places in the program, you will get a message to Since the form is referenced in several places in the program, you will get a message to confi
confirm that you want to rename all occurm that you want to rename all occurrences of the namerrences of the name. . ClickClick OKOK..
You are free to choose any name for the form as long as the ".cs" extension is retained. You are free to choose any name for the form as long as the ".cs" extension is retained. We
We hahave ve a a coconvnvenentiotion n (g(gooood d hahabitbit) ) to to ususe e the firsthe first t ththree charree characacterters s of of ththe e naname me of of anan object to indicate the class or type to which the object belongs, in this case "frm".
object to indicate the class or type to which the object belongs, in this case "frm".
Run the application
Run the application
You havYou have just develoe just developed your firsped your first C# t C# proprogragram! m! It does not do It does not do mucmuch h but at but at lealeast you have ast you have a running Windows application.
running Windows application. Press
Press F5F5 or or clclicick k on on to ruto run n ththe e prprogograramm
Note that there are two modes of a program, namely
Note that there are two modes of a program, namely design modedesign mode where the program iswhere the program is developed in the integrated development environment (IDE) of Visual Studio and
developed in the integrated development environment (IDE) of Visual Studio and run-timerun-time mode
You can move the focus to the IDE while the program is running but you will not be able to You can move the focus to the IDE while the program is running but you will not be able to cha
change anytnge anythinghing. . If the focus is on If the focus is on youyour r appappliclicatioation, you will have to n, you will have to prepressss Alt-F4Alt-F4 or clickor click on
on to cto clolosse ite it. . IIf thf the foe foccus ius is in Vs in Visisuaual Stl Stududioio, y, you cou can pan preressss Shift-F5Shift-F5 to to clclosose e ththee program.
program.
Change the form's properties
Change the form's properties
A form is anA form is an objectobject or "thing" in the same way that a motor car or a shoe or a person is anor "thing" in the same way that a motor car or a shoe or a person is an objec
object. t. ObjecObjects ts havehave propertiesproperties that descrthat describe their appearibe their appearance and behavance and behaviour. iour. For exampleFor example,, people have names and ID numbers, shoes have size and colour, cars have a make, model and people have names and ID numbers, shoes have size and colour, cars have a make, model and registration number.
registration number. Cl
Clicick k ananywywhehere re on on ththe e foform rm in in dedesisign gn momode de anand d loclocatate e ththee PropertiesProperties windwindow ow whiwhich ch isis no
normrmalally ly dodockcked at ed at ththe e rigrightht-h-hanand d siside of de of ththe e IDIDE. E. If you don'If you don't t sesee e itit, , clclicick k onon View /View / Properties Window
Properties Window.. No
Note tte thahat tht therere are are twe two lio liststs, s, nanamemely tly the phe proroperpertieties ( s ( ) an) and td the ehe eveventnts ( s ( ). ). We We wiwill gll getet to eve
to eventnts s lalateter. r. ThThe e proproperpertieties can eiths can either be er be sosortrted alped alphahabebetiticacally ( lly ( ) or ) or alalphphababeteticicalallyly with
within cain categtegoriories ( es ( ). ). NotNote that se that some prome propeopertierties have bs have bracracketkets aros around thund them so tem so that thhat theyey are listed at the top of the alphabetical list.
are listed at the top of the alphabetical list.
The list of properties has two columns – one for the The list of properties has two columns – one for the name of the property and one for its value. The
name of the property and one for its value. The NameName pr
propeopertrty y alalrereadady y hahas s a a vavalue lue whwhicich h VisVisuaual l StStududioio de
derivrived ed frfrom om ththe e fifile le naname me ththat at we we enenteterered d aboaboveve.. The
The NameName property is the most important property of property is the most important property of any obje
any object. ct. VisVisual Studual Studio providio provides defaes default nameult names s toto ob
objejectcts s bubut t it it is is a a vevery ry gogood od hahabibit t to to chchanange ge ththee name of an object to reflect its function.
name of an object to reflect its function.
You can play aroun
You can play around d witwith h the othethe other r propropertpertiesies. . ChaChange theinge their r valvaluesues,, press
press F5F5 and inspect the effect. Look specifically at the effect of theand inspect the effect. Look specifically at the effect of the following:
following: BackColorBackColor,, ControlBoxControlBox,, OpacityOpacity,, SizeSize,, StartPositionStartPosition,, Text
Text. . Be cBe cararefeful noul not to set to sett OpacityOpacity to 0%! You can also change theto 0%! You can also change the va
value lue of of ththee SizeSize proproperperty ty by by gragrabbbbing ing onone e of of ththe e foform'rm's s hahandlndlererss with the mouse and dragging it.
Save, Close and Reopen your work
Save, Close and Reopen your work
You may close Visual Studio and switch off the computer at any time. You may close Visual Studio and switch off the computer at any time.
Click on
Click on File / Save AllFile / Save All (Alternatively press(Alternatively press Ctrl-Shift-SCtrl-Shift-S oor r cclliicck k oon n )) Click on File / Exit (Alternatively press
Click on File / Exit (Alternatively press Alt-F4Alt-F4 oor r cclliicck k oon n ))
If you exit Visual Studio without saving, you will get a message which will ask you if you want If you exit Visual Studio without saving, you will get a message which will ask you if you want to sav
to save befoe before exitre exit. . ClicClick onk on YesYes..
You can reopen your work at a time that is convenient for you. You can reopen your work at a time that is convenient for you.
Click on
Click on File / Recent ProjectsFile / Recent Projects and select your project.and select your project.
If you want to open an earlier project that does not appear in the list of recent projects, If you want to open an earlier project that does not appear in the list of recent projects, you will have to click on
you will have to click on File / Open / Project /SolutionFile / Open / Project /Solution …… ((oor r ) ) aannd d tthheen n bbrroowswse e tto o tthhee ".s
".sln" file of your proln" file of your projectject. . ClicClick onk on OKOK..
Reference
Reference
http://msdn.microsoft.com/en-us/library/52f3sw5c.aspx
Write your first C# code
Write your first C# code
Add a button to the form
Add a button to the form
Locate the
Locate the ToolboxToolbox window which is normally positioned on the left-hand side of the IDE.window which is normally positioned on the left-hand side of the IDE. If you don't see it, click on
If you don't see it, click on View / ToolboxView / Toolbox.. C
Clilicck k on on ththe e nenexxt t to to ththee Common ControlsCommon Controls group to open the list of common controls.group to open the list of common controls.
Drag a
Drag a ButtonButton object from the toolbox to the form.object from the toolbox to the form. Cha
Change nge the the buttbutton'on'ss NameName propropertperty y toto btnMessagebtnMessage anand d ititss TextText propropertperty y toto MessageMessage.. Position the button in the middle of the form.
Write the code
Write the code
Dou
Double clicble click k on the on the butbuttonton. . ThiThis s wilwill l opeopen n a a codcode e windwindow that will contaow that will contain sometin somethinhingg like the following:
like the following:
For the momen
For the moment, you don't have to t, you don't have to worworry about what all this meary about what all this means. ns. The mosThe most t impimportortantant th
thing is ing is ththat you at you rerealalisise e ththat you at you hahave finave finally arrlly arrivived ed in in ththe e woworld of rld of C#C#. . UnUntitil l nonow, wew, we wer
were e only playinonly playing g aroaround und in in the the gragraphicphical al intinterferface of ace of VisVisual ual StuStudiodio, , whicwhich h is is exaexactlctly y thethe same for other programming languages such as Visual Basic and Visual C++.
same for other programming languages such as Visual Basic and Visual C++.
Things to note
Things to note
Note theNote the tabstabs at the top of the code windoat the top of the code window. w. YoYou can alwayu can always click on thes click on the frmHelloWorld.csfrmHelloWorld.cs [Design]
[Design] tab to see the form design again. The asterisks in the tabs mean that the contenttab to see the form design again. The asterisks in the tabs mean that the content has
has been been chachangenged sid since nce the the laslast st saveave. . ClicClick ok on n and and see see the the astasterierisks sks disadisappeppear.ar. Curly braces
Curly braces, { , { and }, are used to box in and }, are used to box in cecertairtain fragmn fragmentents of the s of the codcode. e. The bracThe braces occes occurur in
in paipairs, mears, meaning that there is ning that there is a a cloclosinsing g brabrace for ce for everevery y opeopening bracning brace. e. The correThe correspospondinndingg ope
opening and ning and cloclosinsing g brabraces are ces are ververticticallally y alialignegned. d. BraBraces that are ces that are not propernot properly ly paipaired arered are one of the most common errors that beginner programmers encounter.
one of the most common errors that beginner programmers encounter. Note the
Note the indentsindents of the of the varvariouious progras program m bloblockscks. . The indenThe indents are ignorets are ignored d by the by the cocompilmpilerer but ass
but assist the human eye to ist the human eye to ideidentifntify how y how the progrthe programmamming parting parts fit s fit intinto one o one anoanotherther. . InIn the figure above
the figure above, , the prograthe programmimming ng parparts ts are boxed are boxed with rectawith rectanglengles s to to shoshow w how how thethey y fitfit entirely into one another like a series of baskets of different sizes.
entirely into one another like a series of baskets of different sizes. Tabs
Tabs
Braces Braces
Type the code
Type the code
TyType pe ththe e fofollllowowining g liline ne of of cocode de at at ththe e poposisitition on of of ththe e ararrorow. w. TyType pe ththe e tetext xt exexacactltly y asas shown
shown. . Pay particPay particular attentular attention to the capitals and semicoion to the capitals and semicolon.lon. -
- ActActualually, the texly, the text betweet between double quon double quotes is a tes is a chacharacracter strter string and is not recoing and is not recognisgnised byed by the compi
the compiler as belonginler as belonging to the C# g to the C# langualanguage. ge. You can type any messaYou can type any message there.ge there. MessageBox
MessageBox.Show(.Show("Hel"Hello lo WorlWorld!"d!");); Run the program (press
Run the program (press F5F5 or or ccllicick k oon n )).. Click on the
Click on the MessageMessage buttbutton. on. You have jusYou have just executt executed your first line of C# ed your first line of C# codcode!e!
Click
Click OKOK in tin the mhe mesessasage bge box aox and cnd clolose se the the proprogrgram (am (clclicick on k on ).).
Things to know
Things to know
Objects belong toObjects belong to classesclasses. . We can plaWe can place mance many butty buttonons s on a on a foform with earm with each one of themch one of them belo
belonginnging g to to the the claclassss ButtonButton in in ththe e sasame me waway y ththat at alall l inindidivividudual al cacars rs is is a a cacar r anand d alalll individ
individual persons is a ual persons is a human. human. Of course, there are sub-claOf course, there are sub-classes and sub-subsses and sub-sub-clas-classes suchses such as
as alall l ststudeudents beinnts being g huhumaman n anand d alall l fufull-ll-titime me ststudeudentnts s bebeing ing ststudeudentnts. s. We We cacan n ththink of ink of objects and classes as
objects and classes as thingsthings oror membersmembers of a certainof a certain typetype oror kind kind ..
In object oriented terminology, we refer to the individual members of a class as
In object oriented terminology, we refer to the individual members of a class as instancesinstances.. When an object of a specific class is created we say that the object is
When an object of a specific class is created we say that the object is instantiatedinstantiated. . FFoorr example, each time that a button is dragged from the toolbox to the form a new instance example, each time that a button is dragged from the toolbox to the form a new instance of the class
of the class ButtonButton is instais instantiatentiated. d. In other wordsIn other words, in general terms a specif, in general terms a specific button is anic button is an object but it is specifically an instance of the class
object but it is specifically an instance of the class ButtonButton.. We
We havhave e menmentiotioned ned befbefore ore thathat t objobjectects s havhavee propertiesproperties that describe that describe their appearancetheir appearance and beh
and behaviaviourour. . The buttThe button in the exampon in the example abovle above has ae has a NameName property that is used to referproperty that is used to refer to it in the c
to it in the codode. e. It alIt also haso has as a TextText property that is displayed to the user during run-time.property that is displayed to the user during run-time. In this example
In this example NameName is is "" btnMessage" btnMessage"andand TextText is is "" Message" Message".. Objec
Objects ts can also can also experieexperiencence eventsevents. In the example above, the button can be clicked in. In the example above, the button can be clicked in which case a
which case a ClickClick event is triggered.event is triggered. The
There are re are manmany y pospossiblsible events for objece events for objects. ts. SeleSelect the button in ct the button in desdesign mode and click onign mode and click on in
in ththee PropertiesProperties wiwindndow to ow to lilist its evst its evenentsts. . You You wiwill see thall see that t ththee ClickClick evevenent t isis connected to an event handler,
An
An eveevent nt handlhandlerer is is a a pipiecece e of of cocode de ththat at wiwill ll be be exexececututed ed whwhen en an an evevenent t ococcucursrs, , foforr ex
examample the ple the ususer er clclicickiking ng on a on a bubuttttonon. . ThThe e fofollollowiwing ng piepiece of ce of cocode de defdefineines s ththe e evevenentt handler for the
handler for the ClickClick event of the button:event of the button: pri
private vate voidvoid btnMessage_Click(btnMessage_Click( objectobject sender,sender, EventArgsEventArgs e)e) {
{
MessageBox
MessageBox.Show(.Show("Hel"Hello lo WorlWorld!"d!");); }
}
This code says that a message box will be showed with the message "Hello World!" when This code says that a message box will be showed with the message "Hello World!" when the button is clic
the button is clicked. ked. Read this line of code as "MesRead this line of code as "Message box dot Show Hello World"sage box dot Show Hello World"..
The first line of code as well as the curly braces was generated by Visual Studio when you The first line of code as well as the curly braces was generated by Visual Studio when you dou
double clicble clicked the buttoked the button. n. You will lateYou will later r undeunderstrstand all the and all the parparts in ts in the firsthe first t line of code,line of code, but for the moment it would suffice to point out that Visual Studio named the event handler but for the moment it would suffice to point out that Visual Studio named the event handler by combining the button's
by combining the button's NameName (("btnMessage""btnMessage") and the event () and the event (ClickClick) with an underscore.) with an underscore. An
An evevenent t hahandndleler r is is alalso so aa methodmethod. . MeMeththodods s arare e pipiececes es of C# of C# cocode de ththat desat descrcribibe e ththee actio
actions done by ns done by objecobjects. ts. MethodMethods are defined in the s are defined in the classclasses to which objects belong.es to which objects belong. Methods have a
Methods have a headerheader and aand a bodybody. . The heaThe header conder consissists of severts of several partal parts,s, inter aliainter alia thethe nam
name of e of the methothe method. d. The headeThe header r of the of the metmethod alwahod always has brackys has brackets (not curlets (not curly bracesy braces) ) atat the
the enend. d. SoSomemetimtimes es thethere re is is sosomemeththing ing bebetwtweeeen n the the brbracackeketsts, , but but sosomemetimtimes es thethere re isis nothing between the brackets.
nothing between the brackets.
It is important to understand that all event handlers are methods, but not all methods are It is important to understand that all event handlers are methods, but not all methods are eve
event nt hanhandledlers. rs. EveEvent handlent handlers are rs are exeexecutcuted ed whewhen n an event occuan event occurs rs whiwhile other methole other methodsds are exec
are executeuted d onlonly y whewhen n thethey y are specare specificificallally y cacallelled. d. The code in The code in the listthe listing aboving above e has twohas two metho
methods, ds, namenamelyly frmHelloWorld()frmHelloWorld() andand btnMessagebtnMessage _ _ Click()Click(), , bbuut t oonnly ly oonne e of of tthheemm,, btnMessage
btnMessage _ _ Click()Click(), is an event handler., is an event handler. Ind
Individividual lines of ual lines of code withicode within n a a metmethod are hod are calcalled stateled statemenments. ts. StatStatemeements are nts are alwalwaysays followed by a semicolon as in the example below:
followed by a semicolon as in the example below: MessageBox
MessageBox.Show(.Show("Hel"Hello lo WorlWorld!"d!");); In
In the the exaexample abovemple above MessageBoxMessageBox is is a a clclasass. s. ThThis is clclasass s anand d alall l itits s memeththodods,s, intinter er alialiaa Show()
Show(), are define, are defined d in the .NET frain the .NET framewmeworkork. . This meaThis means that we do ns that we do not havnot have accese access to s to thethe de
detatailils s of the claof the class or ss or ththe e memeththodsods, , bubut t we are we are wewelclcomome e to use it. to use it. YoYou u cacan n insinspepect thect the available methods for the
available methods for the MessageBoxMessageBox class by erasing the period and everything followingclass by erasing the period and everything following it.
it. If you now typIf you now type e ththe e perperiodiod, , a list of avaa list of availilabable metle methohods wilds will l apappepearar. . We refWe refer to er to thithiss feature of Visual Studio as
feature of Visual Studio as IntelliSenseIntelliSense..
Methods may or may not take
Methods may or may not take parametersparameters, i.e. values between the brackets, separated by, i.e. values between the brackets, separated by com
commasmas. . ParParameameterters s are used during are used during exeexecuticution on and proviand provide de infoinformarmatiotion n to the to the metmethodhod about the job that it must do.
If you type the method followed by an opening bracket a yellow box will appear to indicate If you type the method followed by an opening bracket a yellow box will appear to indicate wh
what at popossssibible le papararammeteteers rs mmay ay be be adaddeded. d. TThehere re arare e 21 21 popossssibible le cocombmbininaatitionons s of of par
parameameters ters for for thethe MessageBoxMessageBox.Show().Show() memeththodod. . PrePress ss ththe e up up anand d dowdown n ararrorows ws to to ststepep through the possibilities.
through the possibilities.
Th
The e fifirsrst t pospossisiblble e cocombimbinanatition on of of paparamrameteeters rs tatakekes s a a sisingnglele stringstring vavalulue e ththat at wiwill ll bebe dis
displplayayed ed whwhen en ththe e memessssagage e box box is is disdisplaplayeyed. d. ThThe e thithird rd popossssibibililitity y tatakekes s twtwo o ststrinringg parameters – one for the message to be displayed and one for the text to be displayed in parameters – one for the message to be displayed and one for the text to be displayed in the cap
the captiotion n babar r of the of the memessssagage e bobox. x. CoCompampare re ththe e fofollollowiwing ng twtwo o ststatatememenents ts wiwith th eaeachch other:
other: MessageBox
MessageBox.Show(.Show("Hel"Hello lo WorlWorld!"d!");); MessageBoxMessageBox.Show(.Show("Hel"Hello lo WorlWorld!"d!",, "Message""Message"););
Note that string parameters are entered between double quotes and numeric parameters Note that string parameters are entered between double quotes and numeric parameters without quotes.
without quotes.
Close the project so that we can start with a new one: Close the project so that we can start with a new one:
Click on
Click on File / Close SolutionFile / Close Solution.. Click on
Click on YesYes to save if the last changes were not savedto save if the last changes were not saved
Add controls from the toolbox
Add controls from the toolbox
Let us start with a new project. Let us start with a new project.
Design the form
Design the form
ClickClick File / New / Project …File / New / Project …
Give a name to the project, "Login". Give a name to the project, "Login".
Browse to the folder where you want to save the project and ensure that the correct folder Browse to the folder where you want to save the project and ensure that the correct folder is in the
is in the LocationLocation box.box. Renam
Rename the file "Form1.cse the file "Form1.cs" to " to "frmLo"frmLogin.cgin.cs". s". The procedure was explaThe procedure was explained in the previousined in the previous chapter.
chapter. Change the
Change the TextText property of the form toproperty of the form to "Login""Login".. Open the
Open the ContainersContainers group in thegroup in the ToolboxToolbox and drag aand drag a GroupBoxGroupBox to the form.to the form. Set the
Set the
Set the TextText prpropopererty of ty of ththe e grogroup up bobox x to an to an ememptpty y ststriring. ng. In otheIn other r wowordsrds, , dedeletlete e ththee current value of the
current value of the TextText property.property. Set the
Set the DockDock property of the group box toproperty of the group box to Bottom Bottom .. Run the program (press
Run the program (press F5F5) and see what the effect is of the) and see what the effect is of the DockDock property if you resizeproperty if you resize the
the foform rm durduring ing rurun-n-titimeme. . CloClose se ththe fe fororm am agagain in (c(cliclick k ).). Drag a button to the group box.
Drag a button to the group box. Change the
Change the NameName property of the button toproperty of the button to "btnClose""btnClose" and theand the TextText property toproperty to "&Close""&Close"..
Do
Doububle le clclicick k on on ththe e bubutttton on anand d enenteter r ththe e fofollllowowining g liline ne of of cocode de in in ththee Click()Click() eventevent handler:
handler: this
this.Close();.Close(); Run the progr
Run the program. am. See if you can find out what the effecSee if you can find out what the effect is t is of the ampersof the ampersandand, "&", in , "&", in thethe Text
Text property of the button.property of the button. Clic
Click on k on the butthe buttonton. . The forThe form will closem will close.. If the form closes correctly, you can set the
If the form closes correctly, you can set the ControlBoxControlBox property of the form toproperty of the form to FalseFalse..
Things to know
Things to know
GroGroup up boxboxes, text boxes, labees, text boxes, labels, buttols, buttons, etc. are ns, etc. are concontrotrols. ls. ConControtrols ls are also objecare also objects ts butbut they are visible (graphical) "things" that we can add to a form.
they are visible (graphical) "things" that we can add to a form. The code in the button's
The code in the button's Click()Click() event handler refers to an object,event handler refers to an object, thisthis, and a method, and a method Close()
Close(). . ThThe kee keywyworord,d, thisthis, refers to the current instance of a class – in this case the, refers to the current instance of a class – in this case the for
form. m. As alwaAs always, a methoys, a method d doedoes somets something on or with the relevahing on or with the relevant objecnt object. t. In this casIn this case thee the current form will be closed when the user clicks on the
current form will be closed when the user clicks on the CloseClose button.button. If
If yoyou u cocompmparare e ththe e butbuttoton n evevenent t hahandlndler er ababovove e wiwith th ththe e butbuttoton n evevenent t hahandlndler er in in ththee previous example, it is import to note that
previous example, it is import to note that thisthis is an object whileis an object while MessageBoxMessageBox is a class.is a class. When a method is called with a class as in
When a method is called with a class as in MessageBoxMessageBox.Show().Show(), the method is referred to, the method is referred to as
as aa staticstatic metmethodhod. . In other wordIn other words, it s, it is not necesis not necessasary to ry to insinstantantiatiate an te an objobject in order toect in order to call a static method.
Add the controls and enter the code
Add the controls and enter the code
DraDrag g two labetwo labels, two text boxls, two text boxes and pictues and picture box to re box to the formthe form. . DraDrag g anoanothether r butbutton to theton to the group box.
group box. Set the labels'
Set the labels' NameName properties toproperties to "lblName""lblName" andand "lblPassword""lblPassword" and theirand their TextText propertiesproperties to
to "Name""Name" andand "Password""Password".. Set the
Set the NameName propropertperties of ies of the text the text boxboxes es toto "txtName""txtName" andand "txtPassword""txtPassword" and and ensensureure that the
that the TextText properties are empty.properties are empty. Set the
Set the PasswordCharPasswordChar property of property of txtPasswordtxtPasswordtoto "*""*".. Set the
Set the NameName of the second button toof the second button to "btnLogin""btnLogin" and itsand its TextText property toproperty to "&L"&Log og in"in".. Use the
Use the guidelinesguidelines in design mode to align all contin design mode to align all controls properrols properly. ly. See the screen print belowSee the screen print below fo
for r an an exexamample of ple of the the alaligignmnmenent t of of thethe GreetingGreeting bubuttttonon. . NeNeat form layoat form layout is ut is exextrtrememelyely important. It creates positive first impressions of a program and is conducive to usability. important. It creates positive first impressions of a program and is conducive to usability.
Set the
Set the NameName of the picture box toof the picture box to "picPhoto""picPhoto".. Cl
Clicick k oon n ththe e nenexxt t to to ththee ImageImage property of the picture box.property of the picture box.
Se
Selelect ct ththee LocLocal al resoresourceurce raradidio o bubutttton on in in ththe e ssububsseqequeuent nt didiaalolog g bobox x aand nd clclicick k oonn .
. BrBrowowse se to to anany y pipictcturure e on on yoyour ur cocompmpututerer, , fofor r exexamamplple e a a phphototogograraph ph of of y
yoouurrsseellff, , aannd d cclliicck k oon n aannd d tthheen n oon n . . ((HHiinntt: : IIf f yyoou u ddoonn''t t hhaavve e a a ppiiccttuurree of
of youyourserself, lf, therthere e are are somsome e scescenes nes of of natnature ure on on "C:"C:\Do\Documcumentents s and and SetSettingtings\s\All All UseUsers\ rs\ Documents\My Pictures\Sample Pictures".)
Play around with the
Play around with the SizeModeSizeMode property of the picture box and examine its effect.property of the picture box and examine its effect. Run the program and check that everything is working.
Run the program and check that everything is working.
Close the form again and enter the following line of code in the
Close the form again and enter the following line of code in the Click()Click() event handler of event handler of the
the Log inLog in button:button: MessageBox
MessageBox.Show(.Show("G"Gooood d daday, y, "" + txt+ txtNamName.Te.Text ext ++ "!""!",, "Lo"Log g in"in");); Run the program again (
Run the program again (F5F5). ). EnEnteter r yoyour namur name in e in ththe text box ane text box and d clclicick on k on thethe GreetingGreeting button.
button. WatcWatch the effect if you enh the effect if you enter other nameter other names.s.
Set the
Set the TabIndexTabIndex propproperterty of y of the text box to 0. the text box to 0. Try to figurTry to figure out what the effece out what the effect of t of this is.this is. Se
Set t ththee AcceptButtonAcceptButton prpropeopertrty y of of the form the form toto "btnLogin""btnLogin". . TTry to firy to figugure oure out t whwhat that thee effect of this is.
Things to know
Things to know
InsInstantances ces of of the the claclassss TextBoxTextBox allallow ow a a useuser r to to ententer er chacharacracter ter strstrings during ings during run-run-timtime.e. While the text box in the form,
While the text box in the form, txtNametxtName, can accept any input, the label suggests to the, can accept any input, the label suggests to the us
user that he/er that he/shshe e mumust entest enter r hishis/h/her name in er name in ththe e bobox. x. ThThe e vavalue typlue typed into the ed into the tetext boxxt box during runtime is assigned to its
during runtime is assigned to its TextText property.property. Ins
Instantances ces of of the the claclassss,, LabelLabel, , are used are used to to proprovide inforvide informatmation or ion or insinstrutructictions to ons to a a useuser.r. The user cannot enter the text during runtime.
The user cannot enter the text during runtime.
A picture box can be used to display a picture during runtime. A picture box can be used to display a picture during runtime. The line of code in the event handler of the
The line of code in the event handler of the GreetingGreeting button containsbutton contains txtName.TexttxtName.Text. . TThhiiss tim
time e we havwe have e ththe e obobjecject t fofollllowowed by ed by a a prpropoperterty. y. ThThee TextText property that is referred to inproperty that is referred to in the code is the exact same property that can be accessed through the
the code is the exact same property that can be accessed through the PropertiesProperties windowwindow dur
during desiing design gn titimeme. . It It is is eaeasy sy to to disdistintinguguisish h prpropeopertrtieies s frofrom m memeththods in ods in ththe e cocode de sisincncee methods are always followed by brackets and properties not.
methods are always followed by brackets and properties not. The first parameter of the
The first parameter of the Show()Show() method consists of three separate character strings thatmethod consists of three separate character strings that are concat
are concatenated by the "+" operator. enated by the "+" operator. This means that the resultThis means that the resulting string is a head-to-ting string is a head-to-tailail co
compomposisitiotion n of of ththe e ththreree e sesepapararate te papartsrts. . The partThe parts s witwithihin n quoquotetes s arare e usused ed as as ththey ey areare,, while the value (contents of the box) of the
while the value (contents of the box) of the txtName.TexttxtName.Text prpropeopertrty is y is ususeded. . ThThusus, if , if ththee user enters "John" into the text box, the effective code becomes:
user enters "John" into the text box, the effective code becomes: MessageBox
MessageBox.Show(.Show("Go"Good od dayday, , JohJohn!n!"",, "Lo"Log g in"in"););
Naming conventions
Naming conventions
A
A cocontntrol shorol should be uld be gigiveven n a a naname me ththat will reflat will reflecect t ththe e purpurpospose e ththereereofof. . CoCompmparare e ththee fol
followlowing two ing two piepiececes s of code of code and deciand decide which verside which version will on will be the be the easeasiesiest t to maintato maintain. in. ThThisis iss
issue ue becbecomeomes s more and more and mormore e impoimportartant nt as as the projecthe project t becbecomeomes s biggbigger er and bigger and bigger witwithh more than one form and many labels, text boxes, buttons, etc.
more than one form and many labels, text boxes, buttons, etc. namespace
namespace WindowsFormsApplication1WindowsFormsApplication1 {
{
pub
public lic partpartial ial clasclasss Form1Form1 :: Form Form {
{
public
public Form1()Form1() { { InitializeComponent(); InitializeComponent(); } } pri
private vate voidvoid button1_Click(button1_Click( objectobject sender,sender, EventArgsEventArgs e)e) {
{
this
this.Close();.Close(); }
} pri
private vate voidvoid button2_Click(button2_Click( objectobject sender,sender, EventArgsEventArgs e)e) {
{
MessageBox
MessageBox.Show(.Show("G"Gooood d daday, y, "" + + textextBotBox1.x1.TexText t ++ "!""!",, "Greeting""Greeting");); } } } } } }
namespace
namespace LoginLogin {
{
pub
public lic partpartial ial clasclasss frmLoginfrmLogin :: Form Form {
{
public
public frmLogin()frmLogin() { { InitializeComponent(); InitializeComponent(); } } pri
private vate voidvoid btnClose_Click(btnClose_Click( objectobject sender,sender, EventArgsEventArgs e)e) {
{
this
this.Close();.Close(); }
} pri
private vate voidvoid btnGreeting_Click(btnGreeting_Click( objectobject sender,sender, EventArgsEventArgs e)e) {
{
MessageBox
MessageBox.Show(.Show("G"Gooood d daday, y, "" + + txttxtNamName.Te.Text ext ++ "!""!",, "Greeting""Greeting");); } } } } } }
It is a good habit to name controls in such a way that the first three letters indicate to what It is a good habit to name controls in such a way that the first three letters indicate to what cla
class the ss the concontrotrol l belobelongsngs. . SomSome e of the of the mosmost t comcommon contrmon control ol claclasssses es witwith h the approthe appropriapriatete prefixes are listed below:
prefixes are listed below: btn btn ButtonButton cmb cmb ComboBoxComboBox chk chk CheckBoxCheckBox cld cld ColorDialogColorDialog dtp dtp DateTimePickerDateTimePicker fod
fod FontDialogFontDialog frm
frm Form Form grp
grp GroupBoxGroupBox img
img ImageImage lbl
lbl LabelLabel lst
lst ListBoxListBox
ofd
ofd OpenFileDialogOpenFileDialog pic
pic PictureBoxPictureBox pnl
pnl PanelPanel prb
prb ProgressBarProgressBar rad
rad RadioButtonRadioButton rtb rtb RichTextBoxRichTextBox sfd sfd SaveFileDialogSaveFileDialog tbc tbc TabControlTabControl tmr tmr TimerTimer txt txt TextBoxTextBox
Comments
Comments
Comments may be added to C# code in order to make notes for yourself or others who will Comments may be added to C# code in order to make notes for yourself or others who will hav
have e to maintto maintain your codeain your code. . ComCommentments are s are ignignoreored d by the by the comcompilepiler r and havand have e no effecno effect t onon progra
program execution. m execution. CommeComments can, therefonts can, therefore, be considered as internal documere, be considered as internal documentationtation of n of what the program statements are doing.
what the program statements are doing. Inline comments
Inline comments are indicated with two forward slashesare indicated with two forward slashes // // . . EveEverytrything fhing follollowinowing theg the // // onon the same line is ignored by the compiler
the same line is ignored by the compiler A
A multilimultiline ne commentcomment stastarts with /* rts with /* and ends with */. and ends with */. MultMultiliiline commne comments caents can n spaspan n sevseveraerall lines and everything between /* and */ will be ignored by the compiler.
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 Every form (and later every class) in a project should include a comment block at the top that indicates the programmer, date and scenario.
Things to do
Things to do
Ensure that the code of your projects is well documented with comments Ensure that the code of your projects is well documented with comments
/* Stu
/* Studedent numnt numbeber r : : 20201010121234345656
S Stutudedent nt nnamame e : P: Piieteter er BBliligngnauautt S Scceennaarriio o : D: Deemmoonnssttrraattiioon on of tf thhe ue usse oe of lf laabbeellss, b, buuttttoonns as annd td teexxtt b boxoxes es on on a a foformrm.. D Daatte e : : 116 6 NNoovveemmbbeer r 22000099 */ */ using
using System;System; using
using System.Collections.Generic;System.Collections.Generic; using
using System.ComponentModel;System.ComponentModel; using
using System.Data;System.Data; using
using System.Drawing;System.Drawing; using
using System.Linq;System.Linq; using
using System.Text;System.Text; using
using System.Windows.Forms;System.Windows.Forms;
namespace
namespace LoginLogin {
{
publ
public ic partpartial ial clasclasss frmLoginfrmLogin :: Form Form {
{
public
public frmLogin()frmLogin() { { InitializeComponent(); InitializeComponent(); } } //E
//Evenvent t hanhandledler r for for the the CloClose se butbuttonton
priv
private ate voidvoid btnClose_Click(btnClose_Click( objectobject sender,sender, EventArgsEventArgs e)e) {
{
this
this.Close();.Close(); //C//Closlose e the the forform m
} } //E
//Evenvent t hanhandledler r for for the the GreGreetieting ng butbuttonton
priv
private ate voidvoid btnGreeting_Click(btnGreeting_Click( objectobject sender,sender, EventArgsEventArgs e)e) {
{
//
//DiDispsplalay y grgreeeetiting ng wiwith th ththe e naname me of of ththe e ususerer
MessageBox
MessageBox.Show(.Show("G"Gooood d daday, y, "" + + txttxtNamName.Te.Text ext ++ "!""!",, "Greeting""Greeting");); } } } } } }
Traffic light example
Traffic light example
Develop a Windows application that will display a traffic light as in the screen print below. Develop a Windows application that will display a traffic light as in the screen print below.
Close button
Close button
Add aAdd a CloseClose button to the form and set the required properties as for the examples above.button to the form and set the required properties as for the examples above. Enter the appropriate code for the
Enter the appropriate code for the Click()Click() event handler.event handler.
Form
Form
Set the form's
Set the form's TextText property to an empty string.property to an empty string. Set the
Set the ControlBoxControlBox property toproperty to FalseFalse.. Set the
Set the FormBorderStyleFormBorderStyle property toproperty to FixedSingleFixedSingle.. Set the StartPosition property to CenterScreen. Set the StartPosition property to CenterScreen.
Picture boxes
Picture boxes
PuPut t ththreree e pipicctuture re boboxexes s oon n ththe e foform rm aand nd nanamme e ththemem "picRed""picRed",, "picYellow""picYellow" andand "picGreen"
"picGreen" respectively.respectively. Load the
Load the images "LightReimages "LightRed.jpg"d.jpg", , "LightY"LightYellow.ellow.jpg" jpg" and and "Light"LightGreen.Green.jpg" jpg" in in the the respecrespectivetive picture boxe
picture boxes. s. You can find these files on the CD You can find these files on the CD that accothat accompaniempanies this tutorial.s this tutorial.
Make sure that the picture boxes are exactly the same size and that they are positioned Make sure that the picture boxes are exactly the same size and that they are positioned exactly on top of one another.
exactly on top of one another. Set
Set SizeModeSizeMode property of the picture boxesproperty of the picture boxes Zoom Zoom .. Set the
Set the VisibleVisible property of all picture boxes toproperty of all picture boxes to FalseFalse..
Traffic light buttons
Traffic light buttons
Add theAdd the RedRed,, YellowYellow andand GreenGreen buttons as in the screen print.buttons as in the screen print. Set the buttons'
Set the buttons' TextText properties as in the screen print.properties as in the screen print. Set the buttons'
Set the buttons' NameName properties toproperties to btnRedbtnRed,, btnYellowbtnYellow andand btnGreenbtnGreen respectively.respectively. Enter the following code for the
Enter the following code for the Click()Click() event handler of theevent handler of the RedRed button:button: pic
picRed.Red.VisiVisible ble == truetrue;; picYellow.
picYellow.Visible Visible == falsefalse;; picGreen.V
picGreen.Visible isible == falsefalse;;
Study the code above and then enter the appropriate code for the
Study the code above and then enter the appropriate code for the Click()Click() event handlersevent handlers for the other two buttons.
for the other two buttons.
Run the program and click on the buttons in turn. Run the program and click on the buttons in turn.
Things to understand
Things to understand
The three picture box objects are initially all invisible. 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 When a button is clicked, one of the picture boxes is set to be visible while the others are set to be invisible.
set to be invisible. The code
The code pic
picRed.Red.VisiVisible ble == truetrue;; picYellow.
picYellow.Visible Visible == falsefalse;; picGreen.V
picGreen.Visible isible == falsefalse;; can be replaced with
can be replaced with picRed.Show(); picRed.Show(); picYellow.Hide(); picYellow.Hide(); picGreen.Hide(); picGreen.Hide(); with the same effe
with the same effect. ct. The firsThe first t seset t of lines sets the value of of lines sets the value of proproperperties whilties while e the secthe second setond set calls methods of the
calls methods of the PictureBoxPictureBox class that sets theclass that sets the VisibleVisible propropertperty. y. NotNote specie specificficalallyly that properties do not have brackets while methods always have.
Resources
Resources
http://msdn.microsoft.com/en-us/beginner/bb308730.aspx http://msdn.microsoft.com/en-us/beginner/bb308730.aspxKeywords
Keywords
You should make sure that you know what each of these items mean or where they are used. You should make sure that you know what each of these items mean or where they are used.
.NET framework .NET framework + Operator + Operator AcceptButton AcceptButton Ampersand Ampersand Application Application BackColor BackColor Brace Brace Bracket Bracket Button Button Class Class Click
Click eventevent Close() Close() Code window Code window Comment Comment Concatenate Concatenate Control Control ControlBox ControlBox Convention Convention Desig
Design n modemode Directory Directory Dock Dock Double quote Double quote Drag Drag Event Event Event handler Event handler File File Folder Folder Form Form Form handler Form handler Form layout Form layout FormBorderStyle FormBorderStyle Graphical interface Graphical interface GroupBox GroupBox Hide() Hide() IDE IDE Image Image Indent Indent Inline comment Inline comment Instance Instance Instantiate Instantiate IntelliSense IntelliSense Label Label MessageBox MessageBox Method Method Minimise Minimise Multiline comments Multiline comments Name Name Naming convention Naming convention Numeric values Numeric values Object Object Opacity Opacity Parameter Parameter PictureBox PictureBox Project Project Property Property Run-time Run-time Save Save Show() Show() Single
Single quotequotess Size Size SizeMode SizeMode Solution Explorer Solution Explorer StartPosition StartPosition Statement Statement Static method Static method String value String value Sub-class Sub-class Tab Tab TabIndex TabIndex Text Text TextBox TextBox this this Toolbox Toolbox Usability Usability Visible Visible Visual Studio Visual Studio Width Width Windows Explorer Windows Explorer
Windows Forms application Windows Forms application
Short cuts
Short cuts
-E -E Alt-F4 Alt-F4 Ctrl-Shift-S Ctrl-Shift-S F5 F5 Shift-F5 Shift-F5Icons and Buttons
Icons and Buttons
C
Coonncceepptts s : : NNoorrmmaall Fi
Files les anand d fofoldelders rs : : NoNormrmal al bebetwtweeeen n quoquotestes, , e.e.g. g. "f"frmrmLoLogingin.c.cs"s".. Cla
Classsses and Coes and Contrntrols ols : Gree: Green, e.gn, e.g.. ColorColor,, PictureBoxPictureBox P
Prrooppeerrttiiees s : : BBoolldd, , ee..gg.. NameName P
Proropepertrty y vavalulues es : : As As it it aappppeearars s in in cocodede, , e.e.g.g. "John""John",, 1010,, CenterScreenCenterScreen.. M
Meetthhoodds s : : BBoolld d wwiitth h bbrraacckkeettss, , ee..gg.. Show()Show() E
Evveenntts s : : BBoolld d wwiitth h tthhe e wwoorrd d ""eevveenntt"", , ee..gg.. ClickClick eventevent E
Evveennt t hhaandndlelerrs s : : AAs s ffoor r mmeetthhoodsds, , ee..g.g.Close()Close().. R
Exercises
Exercises
1.
1. CrCreaeate a te a WiWindndowows Fors Forms apms applplicicatatioion n to alto allolow a w a ususer to ener to enteter hisr his/h/her tier titltle, nae, name anme andd sur
surnamname. e. Add labAdd labelsels, text box, text boxes, butes, buttontons and a s and a cocombo box as in the exambo box as in the examplmple. e. WheWhenn th
the e ususer er cclilicckks s on on ththee GreetingGreeting bubuttttonon, , a a memessssagage e shshouould ld be be didispsplalayeyed d ththat at wiwillll concatenate the user entries in the three fields and display a greeting.
concatenate the user entries in the three fields and display a greeting. Hint: Use the
Hint: Use the ItemsItems collection in the Properties window of the combo box to enter thecollection in the Properties window of the combo box to enter the po
possssiblible e tititltleses. . DuDuriring ng rurun-n-titimeme, , yoyou u cacan n obobtatain in the the ususerer's 's seseleclectiotion n frfrom om ththe e TeTextxt property as for the text boxes.
property as for the text boxes.
2.
2. CreCreate ate a Wia Windondows Fws Formorms aps applicplicatiation ton that hat wilwill all allow low the the useuser to r to selselect ect a spa sportorts cos code frde fromom a set
a set of radio buttof radio buttonsons. . WheWhen the n the useuser r cliclicks the buttocks the button, an n, an appapproprropriatiate messae message andge and pic
picturture must be e must be disdisplaplayedyed. . YoYou u may be creamay be creativtive with the e with the mesmessasagesges. . See if you can findSee if you can find o
ouut t wwhhaat t tthhe e ddiiffffeerreenncce e iis s bbeettwweeeen n tthhe e ddeeffaauullt t eevveennt t ffoor r a a rraaddiio o bbuuttttoonn,, CheckedChanged
CheckedChanged, and the, and the ClickClick event.event. Hi
Hintnt: : ThTherere e arare e sosome me exexamample ple picpictutureres s avavaiailalable ble on on the the CD CD ththat at acaccocompmpananies ies ththisis tu
tutotoriarial. l. CoCopy py ththesese e intinto o ththe e "\"\binbin\D\Debebug" foldug" folder er of of yoyour ur apappliplicacatition on anand d ususe e ththee ImageLocation
ImageLocation property to load them into the picture box, for example:property to load them into the picture box, for example: picSport.I
3.
3. CoConsnsideider thr the foe follollowiwing sng scecenarnarioio: : YoYou hau have bve beeeen asn askeked to dd to devevelelop a pop a prorogragram thm that cat canan be used by
be used by a a lelectctururer er to obtato obtain in ststatatisistitics on cs on ththe e ststudeudentnts s in his in his clclasass. s. DeDevevelolop p anan application with a form as in the example and characteristics as below:
application with a form as in the example and characteristics as below:
So
Solutlutioion n sasaveved d as as : : ChCh01E01Ex0x03.3.slslnn Form
Form - Sa
- Savveed d aas s : : ffrrmmNNaammeeSSuurrnnaammee..ccss -
- CCaappttiioon n : : NNaamme e aannd d SSuurrnnaammee -
- HeHeigight ht & W& Wididth th : 2: 235 35 & 4& 46767 -
- StaStartirting posng positioition in the middn in the middle of the scle of the screereenn -
- CanCannot bnot be rese resized dized durinuring run-g run-timtimee -
- Cannot Cannot be minimbe minimised oised or maximr maximised duised during runring run-time-time Controls:
Controls: -
- LabLabels aels and texnd text boxes ft boxes for namor name and sure and surnamnamee -
- LabLabel and dael and date/te/time btime box for dox for date of biate of birthrth -
- LabLabel anel and comd combo box bo box for dfor degreegree.e. -
- AvailAvailable itemable items: B.Scs: B.Sc., B.Com.., B.Com., B.A., B.T, B.A., B.Th., B.Ed.h., B.Ed., Other., Other. -
- IteItems in the box musms in the box must alwayt always be sortes be sorted alphad alphabetibeticacallylly.. -
- GroGroup with raup with radio butdio buttontons as in the exas as in the examplemple. . A studeA student can stnt can study for onudy for only one degly one degreeree at a time.
at a time. -
- GroGroup with cheup with check boxeck boxes as in the exams as in the example. ple. A studeA student may havnt may have subjee subjects frcts from moreom more than one year and must therefore be able to select more than one box.
than one year and must therefore be able to select more than one box. -
- Button to Button to clear all cclear all contentontents with shos with shortcut artcut as indicas indicatedted -
- Button to eButton to exit applixit applicatiocation with shon with shortcut artcut as indicas indicatedted -
- All coAll contrntrols mols must be prust be properoperly namly nameded -
- All conAll controtrols must be propls must be properlerly aligny aligned and spaed and spacedced -
- The useThe user shoulr should be able to move focd be able to move focus from one cous from one controntrol to the other in a logical to the other in a logicall order with
order with Tab/Shift-TabTab/Shift-Tab.. Code
Code -
- FFoorr ClearClear buttonbutton -
- FFoorr ExitExit buttonbutton Comment
Comment -
- StuStudendent numt numberber, na, name anme and datd datee -
- RunnRunning coing commemment to explant to explain whain what the codt the code is doinge is doing 4.
4. DDeevevelolop a sp a simimpple le foform arm as is in tn the he eexaxampmplele. . WWhehen tn the he ususerer cl
clicicks ks on on ththe e butbuttoton, n, the the foformrm's 's babackckgroground und cocoloulour r mumustst ch
chanange ge to to liglight ht blblue ue anand d the buttthe button on mumust st chchanange ge toto GreyGrey.. When the user clicks the
When the user clicks the GreyGrey button, the form's backgroundbutton, the form's background colour must change back to grey and the button to
colour must change back to grey and the button to Light blueLight blue.. Hint: To obtain a colour, type the class
Hint: To obtain a colour, type the class ColorColor followed by afollowed by a period and use