7
Icons,GroupBoxes,CheckBoxes,
RadioButtons
ReviewandPreview
YoushouldfeelverycomfortableworkingwithintheVisualC#environmentby
nowandknowthethreestepsofbuildingaproject.
In this class, we learn about three more controls relating to making choices in
VisualC#:groupboxes,checkboxes,andradiobuttons.Wewilllookatanother
waytomakedecisionsusingtheswitchstructure.We’llhavesomefunmaking
iconsforourprojects.And,youwillbuildasandwichmakingproject.
Icons
Have you noticed that whenever you design or run a Visual C# project, a
little picture appears in the upper left hand corner of the form. This picture is
calledanicon.IconsareusedthroughouttheWindowsenvironment.Thereare
probablylotsoficonsonyourWindowsdesktop-eachoftheserepresentssome
kindofapplication.LookatfilesusingWindowsExplorer.Noticeeveryfilehas
an icon associated with it. Here is a blank Visual C# form:
TheiconseenisthedefaultVisualC#iconforforms.It’sreallykindofboring.
Using the Icon property of the form, you can change this displayed icon to
something a little flashier. Before seeing how to do this, though, let’s see how
youcanfindothericonsorevendesignyourownicon.
CustomIcons
Aniconisaspecialtypeofgraphicsfilewithanicoextension.Itisapicture
witha specific sizeof32 by32 pixels.Theinternet hasawealth offree icons
youcandownloadtoyourcomputeranduse.Doasearchon‘free32x32ico
files’. You will see a multitude of choices. One site we suggest is:
/>Atsuchasite,yousimplydownloadtheicofiletoyourcomputerandsaveit.
It is possible to create your own icon using Visual Studio. To do this, you
needtounderstanduseoftheMicrosoftPainttool.Wewillshowyouhowto
create a template for an icon and open and save it in Paint. To do this, we
assumeyouhavesomebasicknowledgeofusingPaint.Formoredetailsonhow
tousePaint,gototheinternetandsearchfortutorials.
Tocreateaniconforaparticularproject,inSolutionExplorer,right-clickthe
project name, choose Add, then New Item. This window will appear:
Asshown,expandVisualC#ItemsandchooseGeneral.Then,pickIconFile.
NameyouriconandclickAdd.
A
generic
icon
will
open
in
the
Microsoft
Paint
tool:
Theiconisverysmall.Let’smakeafewchangestomakeitvisibleandeditable.
First,resizetheimageto32x32pixels.Then,usethemagnifyingtooltomake
theimageaslargeaspossible.Finally,addagridtothegraphic.Whendone,I
see:
At this point, we can add any detail we need by setting pixels to particular
colors. Once done, the icon is saved by using the File menu. The icon will be
saved in your project file and can be used by your project. The icon file
(Icon1.ico in this case) is also listed in Solution Explorer:
AssigningIconstoForms
As mentioned, to assign an icon to a form, you simply set the form’s Icon
property.Let’stryit.
StartVisualC#andstartanewproject.Ablankformshouldappear.Goto
the properties window and click on the Icon property. An ellipsis (...) button
appears.Clickthatbuttonandawindowthatallowsselectionoficonfileswill
appear. Look for an icon you downloaded or created and saved (if you did it).
Selectanicon,clickOpeninthefilewindowandthaticonisnow‘attached’to
your form. Easy, huh? In the \VCSKids\VCS Projects\Sandwich folder is an
iconwewilluseforaproject(Sandwich.ico).WhenIattachmysandwichicon,
theformlookslikethis:
You’llhavealotoffunusinguniqueiconsforyourprojects.It’snicetoseea
personaltouchonyourprojects.
GroupBoxControl
Agroupboxissimplyacontrolthatcanholdothercontrols.Groupboxes
provideawaytoseparateandgroupcontrolsandhaveanoverallenable/disable
feature.Thismeansifyoudisablethegroupbox,allcontrolsinthegroupbox
arealsodisabled.Thegroupboxhasnoevents,justproperties.Theonlyevents
ofinterestareeventsassociatedwiththecontrolsinthegroupbox.Writingevent
methodsforthesecontrolsisthesameasiftheywerenotinagroupbox.The
group box is selected from the toolbox. It appears as: In Toolbox:
OnForm(defaultproperties):
Properties
Thegroupboxpropertiesare:
Property
Name
Text
Font
BackColor
ForeColor
Left
Top
Description
Nameusedtoidentifygroupbox.Threeletter
prefixforgroupboxnamesisgrp.
Titleinformationattopofgroupbox.
Setsstyle,size,andtypeoftitletext.
Setsgroupboxbackgroundcolor.
Setscoloroftitletext.
Distancefromleftsideofformtoleftsideof
groupbox(Xinpropertywindow,expand
Locationproperty).
Distancefromtopsideofformtotopsideof
groupbox(Yinpropertywindow,expand
Locationproperty).
Width
Height
Enabled
Visible
Widthofthegroupboxinpixels(expandSize
property).
Heightofgroupboxinpixels(expandSize
property).
Determineswhetherallcontrolswithingroupbox
canrespondtouserevents(inrunmode).
Determineswhetherthegroupbox(andattached
controls)appearsontheform(inrunmode).
LiketheFormobject,thegroupboxisacontainercontrol,sinceit‘holds’other
controls. Hence, controls placed in a group box will share BackColor,
ForeColorandFontproperties.Tochangethis,selectthedesiredcontrol(after
itisplacedonthegroupbox)andchangethedesiredproperties.
Movingthegroupboxcontrolontheformusesadifferentprocessthanother
controls.Tomovethegroupbox,firstselectthecontrol.Notea‘built-in’handle
(looksliketwosetsofarrows)formovingthecontrolappearsattheupperleft
corner:
Clickonthishandleandyoucanmovethecontrol.
PlacingControlsinaGroupBox
Asmentioned,agroupbox’ssingletaskistoholdothercontrols.Toputcontrols
inagroupbox,youfirstpositionandsizethegroupboxontheform.Then,the
associated controls must be placed in the group box. This allows you to move
thegroupboxandcontrolstogether.Thereareseveralwaystoplacecontrolsin
agroupbox:
•Placecontrolsdirectlyinthegroupboxusinganyoftheusualmethods.
•Drawcontrolsoutsidethegroupboxanddragthemin.
• Copy and paste controls into the group box (prior to the paste operation,
makesurethegroupboxisselected).
Toinsurecontrolsareproperlyplaceinagroupbox,trymovingit(usethemove
handle)andmakesuretheassociatedcontrolsmovewithit.Toremoveacontrol
fromagroupbox,simplydragitoutofthecontrol.
Example
Start Visual C# and start a new project. Put a group box on the form and
resizeitsoitisfairlylarge.SelectthebuttoncontrolintheVisualC#toolbox.
Dragthecontroluntilitisoverthegroupbox.Dropthecontrolinthegroupbox.
Movethegroupboxandthebuttonshouldmovewithit.Ifitdoesn’t,itisnot
properlyplacedinthegroupbox.Ifyouneedtodeletethecontrol,selectitthen
presstheDelkeyonthekeyboard.Trymovingthebuttonoutofthegroupbox
ontotheform.Movethebuttonbackinthegroupbox.
Putasecondbuttoninthegroupbox.Putanumericupdowncontrolinthe
group box. Notice how the controls are associated with the group box. A
warning:ifyoudeletethegroupbox,theassociatedcontrolswillalsobedeleted!
Run the project. Notice you can click on the buttons and use the numeric
updowncontrol.Stoptheproject.SetthegroupboxEnabledpropertytoFalse.
Run the project again. Notice the group box title (set by the Text property) is
grayed and all of the controls on the group box are now disabled - you can’t
click the buttons or updown control. Hence, by simply setting one Enabled
property(thatofthegroupbox),wecanenableordisableanumberofindividual
controls.Stoptheproject.ResetthegroupboxEnabledpropertytoTrue.Setthe
VisiblepropertytoFalse(willremainvisibleindesignmode).Runtheproject.
The group box and all its controls will not appear. You can use the Visible
propertyofthegroupboxcontroltohide(ormakeappear)somesetofcontrols
(ifyourprojectrequiressuchastep).Stoptheproject.
ChangetheVisiblepropertybacktoTrue.Placealabelcontrolinthegroup
box. Change the BackColor property of the group box. Notice the background
colorofthelabelcontroltakesonthesamevalue,whilethebuttoncontrolsare
unaffected. Recall this is because the group box is a ‘container’ control.
Sometimes, this sharing of properties is a nice benefit, especially with label
controls. Other times, it is an annoyance. If you don’t want controls to share
properties (BackColor, ForeColor, Font) with the group box, you must change
thepropertiesyoudon’tlikeindividually.Groupboxeswillcomeinveryhandy
withthenexttwocontrolswelookat:thecheckboxandtheradiobutton.You
willseethissharingofcolorpropertiesisaniceeffectwiththesetwocontrols.It
savesustheworkofchanginglotsofcolors!
TypicalUseofGroupBoxControl
Theusualdesignstepsforagroupboxcontrolare:
➢ Set Name and Text property (perhaps changing Font, BackColor and
ForeColorproperties).
➢Placedesiredcontrolsingroupbox.Monitoreventsofcontrolsingroup
boxusingusualtechniques.
CheckBoxControl
Acheckboxprovidesawaytomakechoicesfromagroupofthings.When
a check box is selected, a check appears in the box. Each check box acts
independently.Some,all,ornoneofthechoicesinthegroupmaybeselected.
Anexampleofwherecheckboxescouldbeusedischoosingfromalistofice
creamtoppings.Youmightwantitplain,youmightwantacoupleoftoppings,
you might want it with the works - you decide. Check boxes are also used
individually to indicate whether a particular project option is active. For
example, it might indicate if a control’s text is bold (checked) or not bold
(unchecked).
Check boxes are usually grouped in a group box control. The check box
control is selected from the toolbox. It appears as: In Toolbox:
OnForm(defaultproperties):
Properties
Thecheckboxpropertiesare:
Property
Name
Text
TextAlign
Font
Checked
BackColor
ForeColor
Left
Description
Nameusedtoidentifycheckbox.Threeletter
prefixforcheckboxnamesischk.
Identifyingtextnexttocheckbox.
Specifieshowthedisplayedtextispositioned.
Setsstyle,size,andtypeofdisplayedtext.
Indicatesifboxischecked(True)orunchecked
(False).
Setscheckboxbackgroundcolor.
Setscolorofdisplayedtext.
Ifonform,distancefromleftsideofformtoleft
Top
Width
Height
Enabled
Visible
sideofcheckbox.Ifingroupbox,distancefrom
leftsideofgroupboxtoleftsideofcheckbox(X
inpropertieswindow,expandLocationproperty).
Ifonform,distancefromtopsideofformtotop
sideofcheckbox.Ifingroupbox,distancefrom
topsideofgroupboxtotopsideofcheckbox(Y
inpropertieswindow,expandLocationproperty).
Widthofthecheckboxinpixels(expandSize
property).
Heightofcheckboxinpixels(expandSize
property).
Determineswhethercheckboxcanrespondto
userevents(inrunmode).
Determineswhetherthecheckboxappearsonthe
form(inrunmode).
PayparticularattentiontotheLeftandTopproperties.Noticeifacheckboxis
inagroupbox,thosetwopropertiesgivepositioninthegroupbox,notonthe
form.
Example
StartVisualC#andstartanewproject.Drawagroupbox-wewillalways
use group boxes to group check boxes. Place three or four check boxes in the
groupboxusingtechniquesdiscussedearlier.Movethegroupboxtomakesure
thecheckboxesareinthegroupbox.Runtheproject.Clickthecheckboxesand
seehowthecheckmarksappearanddisappear.Noticeyoucanchooseasmany,
or as few, boxes as you like. In code, we would examine each check box’s
Checked property to determine which boxes are selected. Stop the project.
Change the BackColor of the group box. Notice the check box controls’
backgroundcolorchangestomatch.Thisisaniceresultofusingthegroupbox
asacontainer.
Didyounoticewedidn’thavetowriteanyC#codetomakethecheckmarks
appearorgoaway?Thatishandledbythecheckboxcontrol.Therearecheck
boxevents,however.Let’slookatone.
Events
TheonlycheckboxeventofinterestistheCheckedChangedevent:
Event
CheckedChanged
Description
EventexecutedwhenCheckedpropertyofa
checkboxchanges.
Theeventoccurseachtimeauserclicksonacheckbox,eitherplacingacheck
markintheboxorremovingone.
TypicalUseofaCheckBoxControl
Usualdesignstepsforacheckboxcontrolare:
➢SettheNameandTextproperty.InitializetheCheckedproperty.
➢ Monitor CheckChanged event to determine when control is clicked. At
anytime,readCheckedpropertytodeterminecheckboxstate.
➢ You may also want to change the Font, Backcolor and Forecolor
properties.
RadioButtonControl
Aradiobuttonprovidesawaytomakea“mutually-exclusive”choicefrom
agroupofthings.Thisisafancywayofsayingonlyoneiteminthegroupcan
beselected.Whenaradiobuttonisselected,afilledcircleappearsinthebutton.
Noother buttoninthegroupcanbeselected,orhaveafilledcircle.Thereare
manyplacesyoucanuseradiobuttons-theycanbeusedwheneveryouwantto
makeonlyonechoicefromagroup.Sayyouhaveagameforonetofourplayers
-useradiobuttonstoselectthenumberofplayers.Radiobuttonscanbeusedto
selectbackgroundcolors.Radiobuttonscanbeusedtoselectdifficultylevelsin
arcade type games. As you write more Visual C# programs, you will come to
relyontheradiobuttonasadeviceforchoice.
Radiobuttonsalwaysworkingroupsandeachgroupmustbeinaseparate
group box control. Radio buttons in one group box act independently of radio
buttonsinanothergroupbox.So,byusinggroupboxes,youcanhaveasmany
groups of radio buttons as you want. The radio button control is selected from
thetoolbox.Itappearsas:InToolbox:
OnForm(defaultproperties):
Properties
Theradiobuttonpropertiesare:
Property
Name
Text
TextAlign
Font
Checked
BackColor
ForeColor
Left
Top
Width
Height
Enabled
Visible
Description
Nameusedtoidentifyradiobutton.Threeletter
prefixforradiobuttonnamesisrdo.
Identifyingtextnexttoradiobutton.
Specifieshowthedisplayedtextispositioned.
Setsstyle,size,andtypeofdisplayedtext.
Indicatesifbuttonisselected(True)ornot
selected(False).Onlyonebuttoninagroupcan
haveaTruevalue.
Setsradiobuttonbackgroundcolor.
Setscolorofdisplayedtext.
Ifonform,distancefromleftsideofformtoleft
sideofradiobutton.Ifingroupbox,distance
fromleftsideofgroupboxtoleftsideofradio
button(Xinpropertieswindow,expandLocation
property).
Ifonform,distancefromtopsideofformtotop
sideofradiobutton.Ifingroupbox,distance
fromtopsideofgroupboxtotopsideofradio
button(Yinpropertieswindow,expandLocation
property).
Widthoftheradiobuttoninpixels(expandSize
property).
Heightofradiobuttoninpixels(expandSize
property).
Determineswhetherallcontrolswithinradio
buttoncanrespondtouserevents(inrunmode).
Determineswhethertheradiobuttonappearson
theform(inrunmode).
One button in each group of radio buttons should always have a Checked
propertysettoTrueindesignmode.And,again,ifaradiobuttonisinagroup
box,theLeftandToppropertiesgivepositioninthegroupbox,notontheform.
Example
StartVisualC#andstartanewproject.Drawagroupbox.Remember,each
individual group of radio buttons (we need one group for each decision we
make)hastobeinaseparategroupbox.Placethreeorfourradiobuttonsinthe
group box using techniques discussed earlier. Set one of the buttons Checked
propertytoTrue.Runtheproject.Noticeonebuttonhasafilledcircle(theone
you initialized the Checked property for). Click another radio button. That
button will be filled while the previously filled button will no longer be filled.
Keep clicking buttons to get the idea of how they work. In event methods, we
wouldexamineeachradiobutton’sCheckedpropertytodeterminewhichoneis
selected. Stop the project. Did you notice that, like for check boxes, we didn’t
havetowriteanyC#codetomakethefilledcirclesappearorgoaway?Thatis
handled by the control itself. Change the group box BackColor property and
noticeallthe‘contained’radiobuttonsalsochangebackgroundcolor.
Drawanothergroupboxontheform.Puttwoorthreeradiobuttonsinthat
groupboxandsetonebutton’sCheckedpropertytoTrue.Asalways,makesure
the buttons are properly placed in the group box. Run the project. Change the
selectedbuttoninthissecondgroup.Noticechangingthisgroupofradiobuttons
hasnoeffectontheearliergroup.Rememberthatradiobuttonsinonegroupbox
do not affect radio buttons in another. Group boxes are used to implement
separatechoices.Trymoregroupboxesandradiobuttonsifyouwant.Stopthe
project.
Events
TheonlyradiobuttoneventofinterestistheCheckedChangedevent:
Event
CheckedChanged
Description
EventexecutedwhentheCheckedproperty
changes.
WhenoneradiobuttonactinginagroupattainsaCheckedpropertyofTrue,the
CheckedpropertyofallotherbuttonsinitsgroupissettoFalse.Wedon’thave
towriteC#codetodothis-itisautomatic.
TypicalUseofaRadioButtonControl
Usualdesignstepsforaradiobuttoncontrolare:
➢Establishagroupofradiobuttonsbyplacingtheminthesamegroupbox
control➢Foreachbuttoninthegroup,settheName(giveeachbuttona
similar name to identify them with the group) and Text property. You
mightalsochangetheFont,BackColorandForecolorproperties.
➢InitializetheCheckedpropertyofonebuttontoTrue.
➢ Monitor the CheckChanged event of each radio button in the group to
determinewhenabuttonisclicked.The‘lastclicked’buttoninthegroup
willalwayshaveaCheckedpropertyofTrue.
C#-TheFourthLesson
Bynow,you’velearnedalotabouttheC#language.Inthisclass,welookat
justonenewidea-anotherwaytomakedecisions.
Decisions–SwitchStructure
Inthepreviousclass,westudiedtheifstructureasawayoflettingVisualC#
makedecisionsusingcomparisonoperatorsandlogicaloperators.Wesawthat
theifstructureisveryflexibleandallowsustoimplementavarietyofdecision
logics.Manytimesinmakingdecisions,wesimplywanttoexaminethevalueof
justonevariableorexpression.Basedonwhatevervaluesthatexpressionmight
have, we want to take particular actions in our C# code. We could implement
such a logic using if and else if statements. C# offers another way to make
decisionssuchasthis.
Analternativetoacomplexifstructurewhensimplycheckingthevalueofa
singlevariableistheC#switchstructure.Thepartsoftheswitchstructureare:
• The switch keyword • A controlling variable • One or more case
statementsfollowedbyanvalueterminatedbyacolon(:).Afterthecolon
isthecodetobeexecutedifthevariableequalsthecorrespondingvalue.
•Anoptionalbreakstatementtoleavethestructureafterexecutingthecase
code.
• An optional default block to execute if none of the preceding case
statementshavebeenexecuted.
Thegeneralformforthisstructureis:switch(variable)
{
casevalue1:
[C#codetoexecuteifvariable==value1]
break;
casevalue2:
[C#codetoexecuteifvariable==value2]
break;
.
.
default:
[C#codetoexecuteifnoothercodehasbeenexecuted]
break;
}
In this example, if variable = value1, the first code block is executed. If
variable = value2, the second is executed. If no subsequent matches between
variableandvaluesarefound,thecodeinthedefaultblockisexecuted.
Thiscodeisequivalenttothefollowingifstructure:if(variable==value1)
{
[C#codetoexecuteifvariable=value1]
}
elseif(variable==value2)
{
[C#codetoexecuteifvariable=value2]
}
.
.
else
{
[C#codetoexecuteifnoothercodehasbeenexecuted]
}
Acoupleofcommentsaboutswitch.Thebreakstatements,thoughoptional,
will almost always be there. If a break statement is not seen at the end of a
particular case, the following case or cases will execute until a break is
encountered. This is different behavior than seen in if statements, where only
one “case” could be executed. Second, all the execution blocks in a switch
structure are enclosed in curly braces, but the blocks within each case do not
havetohavebraces(theyareoptional).Thisisdifferentfrommostcodeblocks
in C#. Look at the use of the switch structure in the next project to see an
exampleofitsuse.
Project-SandwichMaker
The local sandwich shop has heard about your fantastic Visual C#
programming skills and has hired you to make a computer version of their
ordering system. What a great place to try out your skills with group boxes,
checkboxes,andradiobuttons!
ProjectDesign
In a project like this, making a computer version of an existing process
(ordering a sandwich), the design steps are usually pretty straightforward. We
askedthesandwichshophowtheydothingsandthisiswhattheytoldus:
• Three bread choices (can only pick one): white, wheat, rye • Five meat
choices (pick as many as you want): roast beef, ham, turkey, pastrami,
salami•Threecheesechoices(canonlypickone):none,American,Swiss
• Six condiment choices (pick as many as you want): mustard,
mayonnaise,lettuce,tomato,onion,pickles
Itshouldbeobviouswhatcontrolsareneeded.
Wewillneedagroupofthreeradiobuttonsforbread,agroupoffivecheck
boxesformeat,agroupofthreeradiobuttonsforcheese,andsixcheckboxes
for condiments. We’ll add a button for clearing the menu board, a button to
‘build’thesandwich,andatextbox,withalabelfortitlinginformation,where
wewillprintoutthesandwichorder.ThisprojectissavedasSandwichinthe
courseprojectsfolder(\VCSKids\VCSKProjects).
PlaceControlsonForm
Start a new project in Visual C#. Place and resize four group boxes on the
form. Place three radio buttons (for bread choices) in the first group box
(remember how to properly place controls in a group box). Place five check
boxes(formeatchoices)inthesecondgroupbox.Placethreeradiobuttons(for
cheese choices) in the third group box. Place six check boxes (for condiment
choices) in the fourth group box. Add two buttons, a label and a text box. My
formlookslikethis:
Yes, there are lots of controls involved when working with check boxes and
radiobuttons,andevenmoreproperties.Getready!
SetControlProperties
Setthecontrolpropertiesusingthepropertieswindow:
Form1Form:
PropertyName
PropertyValue
Text
FormBorderStyle
StartPosition
Icon
SandwichMaker
FixedSingle
CenterScreen
[PickoneyoumakewithIconEditoryoucanusemy
littlesandwichicon]
groupBox1GroupBox:
PropertyName
PropertyValue
Name
Text
FontSize
FontStyle
grpBread
Bread
10
Bold
radioButton1RadioButton:
PropertyName
PropertyValue
Name
Text
FontSize
FontStyle
Checked
rdoWhite
White
8
Regular
True
radioButton2RadioButton:
PropertyName
PropertyValue
Name
Text
FontSize
FontStyle
rdoWheat
Wheat
8
Regular
radioButton3RadioButton:
PropertyName
PropertyValue