download - visual c# programming basics

19
; In this tutorial you will learn how to make applications for Windows in C#. You will learn how to use Visual Studio to build simple applications, how to use most of the Windows Forms controls, and several tips on how to publish your application. Made by Davide Vitelaru Visual C# Programming Basics http://davidevitelaru.com/

Upload: truongcong

Post on 26-Jan-2017

230 views

Category:

Documents


3 download

TRANSCRIPT

;

InthistutorialyouwilllearnhowtomakeapplicationsforWindowsinC#.YouwilllearnhowtouseVisualStudiotobuildsimpleapplications,howtousemostoftheWindowsFormscontrols,andseveraltipsonhowtopublishyourapplication.

MadebyDavideVitelaru

VisualC#ProgrammingBasics

http://davidevitelaru.com/

2 VISUALC#PROGRAMMINGBASICS

VISUALC#PROGRAMMINGBASICS 3

GeneralRequirementsTofollowthistutorialyouwillneedthefollowingitems:

‐Knowingthebasicsofatleastoneprogramminglanguage(Toknowwhatvariables,arrays,functions,etc…are)‐AcomputerrunningWindowsXP/Vista/7‐MicrosoftVisualC#Express(Clickfordownload)

YoucanalsouseMicrosoftVisualStudioProfessional,butthisisacommercialversionoftheVisualC#Express,andithasmorefeatures.Wewillnotusemostoftheminthistutorialthough.

Ifyouareinterestedinsomespecificpartofthistutorial,checkoutthetableofcontentsonthelastpagebecauseyoumightfindwhatyouarelookingfor.

QuickStart–YourfirstapplicationInthischapter,youwilllearnhowtomakeanapplicationinVisualStudiofromstarttofinish.Howtocodeit,designitandpublishit.

Step1–CreatingtheprojectTostart,openVisualC#ExpressorVisualStudioandcreateanewprojectbypressingonthe“NewProject”iconintheupperleftcorner.

Inthewindowthatopensyoucanselectyourprojecttype,dependingonwhatyouwanttoprograminC#.TomakeasimpleWindowsapplication,select“WindowsFormsApplication”,nameyourproject“Calculator”(becausethisiswhatwearegoingtodo)andpress“OK”.

4 VISUALC#PROGRAMMINGBASICS

Younowcreatedanewproject.YoumightgetallscaredbyVisualC#’sinterfacebecauseitisverycrowdedandyoudon’tknowwhatmostofthecontrolsdo.Let’stakealookattheinterfaceforabit:thefirstthingthatpop’sintoyoureyesistheformrightinthemiddle.Itisanemptyformandwhatyouhavetodoistotakecontrolsfromthe“Toolbox”,thepanelfromtheleft,andputthemonit.

Youcanseedifferenttypeofcontrolsinthe“Toolbox”:buttons,textboxes,progressbars,andyoucantakeallofthemandplacethemonyourform.Don’tplaceanythingonyourformnow,ifyoudid,selectthemanddeletethem.

Ontherightyouhaveyour“SolutionExplorer”.Whenyoucreateanewproject,youautomaticallycreateanewsolution.Asolutionisacollectionofmultipleprojects,let’ssaywemakeanapplicationcalled“Calculator”(causethisiswhatweactuallydo),and“Calculator”isanapplicationprojectinsidethe“Calculator”solution.Ifwewanttocreateasetupfor“Calculator”,wecreatethesetupprojectinsidethesamesolution.Youwilllearnwhateverythinginthesolutionexplorermeanslater.

Step2–DesigningtheformWhatwewanttocreateisasimplecalculatorapplication.Whatitwilldoistoaddtwonumbersinsertedbytheuser.Tostart,wewillneedthreetext‐boxes:Twoforthetwonumbersthattheuserwantstoaddandthethirdfortheresult.Wewillalsoneedabuttonsothattheusercanpressitandreceivehe’sresult.

Todoallthis,clickonthe“TextBox”controlinthetoolbox,andthenclickonyourform.Asyoucansee,atextboxappearedonyourform.Repeatthisstepagainandcreatetwomoretextboxes.AlignthetextboxesthesamewayIdid:

VISUALC#PROGRAMMINGBASICS 5

Now,selectthebuttoncontrolfromthetoolboxandcreateabuttonontheform.

Good,wenowcreatedallthecontrolsweneedforourapplication.But,thereisaproblem,whyisthebuttonnamed“Button1”?Becausethisishowitisbydefault,tochangethat,weneedtochangeitsproperties.Bydefault,thepropertieswindowisnotopenedinVisualC#.Toopenit,goto“View”andclickon“Properties”.

Thepropertiespanel(obviously)showstheselectcontrolsproperties,suchasheight,width,color,text,etc…Inthiscase,weonlyneedtochangethetextsincethebuttoncanberesizedwithusingthemouse.Clickonthebutton(Makesureyoudon’tdoubleclickit,oritscodewillopen.Ifthathappens,closethetabwiththecodefromthetopofthemiddle‐panel).Onceclicked,thebutton’spropertieswillappearinthe“Properties”window.Scrolldownandgoto“Text”.Toitsrightyouwillsee“Button1”.Changethatto“Add”,andpressenter.

6 VISUALC#PROGRAMMINGBASICS

Yourbuttonnowhas“Add”writtenonit.Verygood,thiswayyoucanediteveryitem’sproperties,eventhetextboxes’.

Also,youmightnoticethattheform’snameis“Form1”.Trytodosomethingaboutit.

HowTo:Clickonanemptyspaceontheform,changetheform’stextpropertyto“Calculator”.

Step3–DebuggingtheapplicationOfcourse,weaddedthecontrolsonourform,butthebuttondoesn’tdoanythingsincewedidn’t“tell”itdotoanything.Youcanseeyourprogramrunningbypressingthe“Debug”button,thegreenarrowinthetoolbar( ).Whenyouclickthedebugbutton,youapplicationwillstart.Itshouldlooksomethinglikethis:

Youprobablytriedtoclickthebuttonalready,andnoticedhowwellheisdoinghisjob.Debuggingisthebestmethodtotestyourapplicationbeforepublishingit.Everytimeyoumakeachangetoit,youdebugittoseeifitworked.Onceyoufinishtheapplication,youbuildtheentireprojectturningeverythingintooneexecutable,andprobablymakeasetupforyourapplication.

Step4–CodingtheapplicationTomaketheapplicationwork,youobviouslyhavetowritesomecode.Ifyouarestilldebuggingyourapplication,closeitandgobacktoyourproject.Now,double‐clickonyourbuttontoopenthecodewindow.Asyoucansee,everythingistabbedintheproject.Youcanalwaysgobacktotheformdesignerbyclickingitstabonthetop.

Withalltheamountofcodethatyouhaveinfrontofyou,youmightgetscared(again!).Don’tworryyouwillgetusedtoit,andtoevenmorethanthat.Ifyouarereadingthistutorial,let’shopeyoualreadyknowthebasicsofanotherprogramminglanguage,ifnotitwillbehardforyoutosearchWikipediaforeverywordyoudon’tunderstand,butitwouldbeuseful.

Thefirststatementsinthecodeimportsomeitemsfromthe.NETFramework.Whatisthatyoumightask,the.NETFrameworkisalargelibraryofcodedsolutionstocommonprogrammingproblemsthatmanagestheexecutionofprogramswrittenspecificallyfortheframework.Tobeclearer,itisalarge

VISUALC#PROGRAMMINGBASICS 7

amountofcodealreadywrittenforyou,soyoucanbuildprogramswithaprettyuserinterfaceandotherthings.Ithelpsyouverymuchbecauseitreducestheamountofthingsthatyouneedtolearntocreatetheentireuserinterface.WeshouldallthankMicrosoftforit:

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

By“importsomethings”fromthe.NETFramework,Imeantimportingsomeclasses.Thoseclassescanbetheforms,theusercontrols,andalltheotherthingsthathelpedusbynowcreatingtheprogram.Youwilllearnthemeaningofthemlater.

Fornow,let’sseetherestofthecode:

namespace Calculator { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { } } }

The“public Form1()”statementisaclassthatisexecutedwhenwestarttheprogram;actually,whenweopentheformnamed“Form1.cs”(“.cs”isfromCSharp).Incaseyoudidnotknow,inC#thecodeisusuallyputbetweencurlybracesjustlikeinJavaandC++.

The“private void button1_Click(object sender, EventArgs e)”isthatclassthatisexecutedwhenweclickthebutton.Insideit,wewillwritethecodethatwilladdthetwovaluesfromthetextboxes.

Note:InC#,twoslashes(//)representsthebeginningofacomment.Acommentisapieceofcodethatisnotexecutedbythecompiler,itisusedtohelpyouorganizeyoucode,andsothatotherprogrammerswillunderstandwhateverypieceofcodemeans.Wewillusecommentsinsideourcodesforbetterexplanation.

Tomakethatbuttonaddthetwovaluesandreturnthesumweneed,wehavetograbthetextcontentfromthetwotextboxes,turnittointegers,addthem,andchangethetextofthethirdtextboxtothesum.Itisverysimple:

double val1, val2; //We declare two double type variables //We assign to the first variable the value of the text box //Since the text box cand hold a string, it must be converted //to a double to assign it to "val1".

8 VISUALC#PROGRAMMINGBASICS

//Note that we assign using “=” as an operator val1 = Double.Parse(textBox1.Text); //Double.Parse("string") converts the string put into the brackets //and assigns it to a double //Same thing for the second variable val2 = Double.Parse(textBox2.Text); //Now we are doing the exact oposite, we take the two //double values and we convert their sum to a string //using the .ToString() command textBox3.Text = (val1 + val2).ToString();

Nowthatwefinishedyoumightwanttodebugyourprojectandseeifitworks.

Whatwedidiseasytoexplain;wedeclaredtwovariablesandassignedthevaluesofthetwotextboxesafterweconvertedthemfromstringstointegers.Then,wechangedthetextofthethirdtextboxintothesumofthetwovariables,andweconvertedittoastringinthesametime.Andwedidallofthisattheclickofabutton.

Step5–PublishingyouapplicationWhatyouhavetodoistocreateaniconforyourapplication,changeitspublishingsettingsandmakeasetupforit,butwewillskipthesestepsastheyarenotrelatedtobasicC#programming.

Note:Checkoutthe“AdvancedVisualC#Programming”tutorialonceyoufinishthisone.

UnderstandingVisualC#Great,nowthatyoumadeyourfirstapplicationyoucangoevendeeperintoC#andunderstandhowmostthingswork,andsomeextrathingsthatwillmakeyourapplicationworkbetter.

ControlnamesFirstofall,oneimportantthingthatyouhavetoknowisthateveryitemonyourformhasaname.AndIamnottalkingabout“TextBox”or“Button”,butabouttheir“Name”property.

VISUALC#PROGRAMMINGBASICS 9

Gobacktoyourformsdesignerandclickonthefirsttextbox.Inthepropertywindow,youwillseethatitsnamepropertyis“textBox1”.Inourpreviouscode,wetookthevaluefromthistextboxbythefollowingmethod:

val1 = Double.Parse(textBox1.Text);

Howdoesthiswork?Let’sforgetabouttheconversionforafewseconds,andseewhatweactuallyassignedtothevariable(consideringthatthetextboxalreadyholdsadoublevalue).

val1 = textBox1.Text;

Weassignedthespecificpropertyofacontroltoavariable.Thecorrectsyntaxis:

variable = control.property;

Thisishowitalwaysworks.Ofcourse,wecandotheexactoppositeandassigntothecontrol’spropertyacertainvariablejustlikewedidearlier:

textBox3.Text = (val1 + val2).ToString();

Thenamesareusedtodistinguishbetweenthecontrolsontheform.

Youcandothesamethingwithbuttons,justclickonabutton,andchangeitsnameproperty.Itisrecommendedthatyourenameyourbuttonssothatyouknowwhateachofthemdoes.

EventsandclassesWhenyoudoubleclickabutton,youareautomaticallyredirectedtoyourcodewhereanewfunctionappears.Thatfunctionwillbeexecutedwhenyouclickthebutton.Youcanrunanyotherfunctionwhenyouclickthebutton,allyouhavetodochangetheeventthatoccurswhenyouclickit.Todothat,gotoits

propertywindow,andclickonthe“Events”button( ).Ontheleftsideofthetablethatjustappearedbellowyouwillseetheevents,andontherightsideyouwillseewhathappens(Whatfunctionisexecuted)whenthateventoccurs.

Asyoucansee,whenweClickthebutton,thebutton1_Clickfunctionisexecuted.Thatfunctionhasbeenautomaticallywrittenforyouwhenyoudouble‐clickthebutton.Ofcourse,thesamefunctioncanbeexecutednomatterwhateventoccurs,forexample,gototheMouseHoverevent,andtypebutton1_Clicktoitsleft.Fromnow,youdon’thavetoclickthebutton,allyouhavetodoisplacethecursoraboveitandthebutton1_Clickfunctionwillrun,addingthetwonumbers.

Youcanalsodeclareanewfunctiontodothejob,andcallitwhenyouclickthebutton.Typesomewherebelowthebutton1_Clickfunction:

double AddNumbers(double val1, double val2) { }

ThisishowwedeclareanewfunctioninC#.Thecorrectsyntaxis:

10 VISUALC#PROGRAMMINGBASICS

value_returened function_name(parameter_type parameter_name) { code }

TheAddNumbersfunctionwillreturnthesumofthetwonumbers.Typeinsidethetwocurlybraces:

return val1 + val2;

“return”isusedtospecifywhatvaluethefunctionwillreturnwhenitiscalled.Tocallthisfunction,deletethecodeinthebutton1_Clickfunctionandtype: private void button1_Click(object sender, EventArgs e) { double val1 = double.Parse(textBox1.Text); double val2 = double.Parse(textBox2.Text); textBox3.Text = AddNumbers(val1, val2).ToString(); }Asyoucansee,wecanassignavaluetoavariablewhenwedeclareit.WeusedtheAddNumbersfunctiontoaddthetwonumbers.Howdoesthiswork?

Form1

Buttonisclicked

2

2

4

button1_Click–Functionisexecuted:

val1val2

AddNumbers(val1,val2)

returnval1+val2

VISUALC#PROGRAMMINGBASICS 11

Notehowthebutton1_ClickfunctionpassesthevaluestotheAddNumbersandthenassignsthemtothethirdtextbox.

Debugyourapplicationandyouwillnoticethatitwillwork.Thebestpartinusingfunctiontodoyourjobisthatyoucanusethemmultipletimeswithoutyouhavingtowritethesamecodealloveragain.

Ifyouhavetoomanyfunctions,yousourcecodemightgetreallycrowded.Inthiscaseyoumightwanttocreateaclasstoholdalloftheminoneplace.

Tocreateaclassinyourproject,rightclickonyourprojecticoninthe“SolutionExplorer”andaddanewclass:

Nameit“Calculator.cs”.Onceyoucreateit,itwillappearinthesolutionexplorer,itwillautomaticallyopen,andyouwillhavethis:using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Calculator { class Calculator { } }

Insidetheclass,cut/pastetheAddNumbersfunction,andchangethefollowingline: public double AddNumbers(double val1, double val2)

Wetyped“public”beforedeclaringthefunctionsowecanuseitoutsidethisclass.

Now,gobackto“Form1.cs”anddeclaretheclassrightontopoftheMainfunction:

Calculator Calc = new Calculator();

12 VISUALC#PROGRAMMINGBASICS

Thecorrectsyntaxis:

ClassName WhatNameYouWantToUse = new ClassName();

Nowthatwedeclaredtheclass,weneedtousethefunctionfromitnamed“AddNumbers”.Todothat,changethefollowinglineofthebutton1_Clickfunction:

textBox3.Text = Calc.AddNumbers(val1, val2).ToString();

Thisway,youcanusetheclassonmultipleforms.

Homework:Makeanewbuttonandanewfunctionnamed“MultiplyNumbers”,andmakeitmultiplythetwonumberswhenthebuttonispressed.

Note:tomultiplytwonumbersinC#,youcanusethe“*”operator.(“­tosubtract,and\todivide”).

Trydoingitbyyourselfbeforereadingthecode.

Code:

Calculator.cs

public double MultiplyNumbers(double val1, double val2) { return val1 * val2; }

Form1.cs

private void button2_Click(object sender, EventArgs e) { double val1 = double.Parse(textBox1.Text); double val2 = double.Parse(textBox2.Text); textBox3.Text = Calc.MultiplyNumbers(val1, val2).ToString(); }

VISUALC#PROGRAMMINGBASICS 13

SolutionsandProjectsItistimetolearnhowthesolutionexplorerworks.

FiletypesAllyouhavetocareaboutinthesolutionexploreraretheforms,classesandreferences.

Theformshavethefollowingicon: andtheyareactuallyacollectionoftwoclasses,onehandlesthedesignbutyoudon’twriteinthatfile,insteadyouarrangethecontrolusingthedesignerthatwritesthecodebyitselfinthedesignerclass,andtheotheroneisthecodeclass.Right‐clickingontheformiconwillgiveyoutheoptiontoopeneitherthecodeorthedesigner.

Theclasseshavethefollowingicon: andtheyarejustindependentfileswithcode.“Program’s”isthemainclassofyourproject,andyoumustnotmodifyit.

Thereferencesareallinsidethisfolder: ,andtheyusuallyrepresentthepiecesofthe.NETFrameworkthatyouareusing.Also,ifyouareusinganyotherclasslibraryitwillappearthere.

Resourcesusuallyrepresenttheimagesthatyouimportedintoyourproject.Theycanbefoundallinthisfolder: .

FilesystemYoumightaskyourselfafteryouworkatanapplication“Whereexactlyismyapplication?”.Tofindtheexecutablecreatedasaresultofyoubuildingyourproject,gotoyourdocumentsfolders,in“VisualStudio2008”(Dependingontheversionyouhave)andgoto:

Projects/<ProjectName>/<ProjectName>/bin/Debug/<ProjectName>.exe

OtherprojecttypesThischapterisnotthatimportantandyoucanskipitifyouarenotinterestedinothertypesofprojects.

WindowsAsyouhavenoticedwhenyoucreatedanewproject,therearemanyothertypesofprojects.ThisiswhatwehaveintheWindowscategory:

The“WindowsFormsApplication”projectiswhatwepreviouslymade.Itisjustasimpleapplicationwithauserinterface.Ontheotherhand,the“ConsoleApplication”isasimpleC#applicationprojectwithouttheuserinterface,itworksinsidetheconsole.

14 VISUALC#PROGRAMMINGBASICS

The“ClassLibrary”isactuallyaprojectfullofclasses.Onceyoucompiletheproject,youwillendupwitha“.DLL”file(DynamicLinkLibrary).Youcanaddthatfileasareferencetoyourprojectsoyoucanusetheclassesinsidethelibrary.

Theotherprojecttypesareadvancedandyouwilllearnwhattheyaregoodforattherighttime.

WebTherearealsoothercategoriesofVisualC#projecttypes:

Webprojects–TheseareforASP.NETWebDevelopers:

SilverlightSilverlightdevelopment–IncaseyouwanttoprogramSilverlightapplications:

XNAGamesAlso,lastbutnotleast,XNAprojectsforgame‐makingusingC#:

Forthelasttwoprojectcategoriesyoumustinstallplug‐ins.Don’tworry,theyarefreetodownloadfromtheinternet,howyouwilllearntousethemisthebiggestproblem.

SetupProjectsIncaseyouhaveVisualStudioProfessionalinstalled,under“OtherProjectTypes”in“SetupandDeployment”youhavethis:

Thesetupprojectistheeasiestwaytocreateadecentandcustomizablesetupforyourproject.

VISUALC#PROGRAMMINGBASICS 15

VisualC#SyntaxThischapterwillshowyousomebasicC#codefordoingdifferentoperations.

Variables&Operations string MyString = "123456"; int MyInt = 24; double MyDouble = 15.6; MyString = "dav"; //Simple assigning MyString = MyDouble.ToString(); //Double to string conversion; //Int to string to double conversion MyDouble = double.Parse(MyInt.ToString()); //This is because you need a sting between thos brackets. MyInt = Int32.Parse(MyDouble.ToString()); //Same here; MyInt += 1234; //This is the += operation, that means you //assign to "MyInt" MyInt + 1234; //Equivalent: MyInt = MyInt + 1234; MyDouble = double.Parse(MyInt.ToString()) + 15;

Loops bool ok=true; // boolean can hold true or false values int i = 0; //while... do loop while (ok==true) { i++; //This adds one unit to i if (i==1000) ok=false; } //for loop for (i=0; i<=1000; i++) { if (i == 5000) break; //break is used to end the loop }

Decisions //if ... then condition int i = 4; bool ok=false; if (i / 2 == 2) { ok = true; } else { i++; } string String = "1234"; //Notice that C# is case-sensitive

16 VISUALC#PROGRAMMINGBASICS

//This is the switch-case command //it works like multiple if's switch (String) { //This happens when no other value works default: break; //In CASE String is "12345", this is what happens case "12345": { i=1; break; //Always remember to break } case "412": { i = 4; break; } }

FileOperationsusing System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; //Notice how we are using the system IO for file operations namespace Calculator { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string FilePath="C:\\Users\\Bubby\\Documents\\1234.txt"; //Remember to use \\ instead of \ because it will throw you an error //Writing to files StreamWriter Name = new StreamWriter(FilePath); Name.WriteLine("First line"); Name.Write("Second line, but not ended"); Name.Close(); //NEVER forget to close //Reading from files StreamReader OtherName = File.OpenText(FilePath); string Something = OtherName.ReadLine(); //Reading a line string AllContent = OtherName.ReadToEnd(); //Reading everything to end OtherName.Close(); }

VISUALC#PROGRAMMINGBASICS 17

WindowsFormsControlsInthischapteryouwilllearnhowtousemostofthecontrolsthatyoucanfindinyourtoolbox.Wearestillgoingtoworkonthecalculatorprojectuntilwereachsomecontrolthatwecan’tuseinsuchaproject.Also,keepinmindthatyouwilllearntousesomeeasycontrolinthischapter,formoredifficultcontrols,seethe“AdvancedVisualC#Programming”tutorial.

FormsThisisamust‐readitembecauseyouwillneedtoknowhowtomakeyourformlookbetter.Forstart,ourmainformincalculatornamed“Form1”isresizable,evenifithasonly4controlsinit.Onceyouresizeit,itlooksuglysogotoitspropertiesinFormBorderStyleandchangeitto“FixedSingle”.Thiswayyoucan’tresizeitanymore.

Eventhoughyoucan’tresizeit,youcanstillmaximizeit(annoying,isn’tit?)sogotoitsMaximizeBoxpropertyandchangethattoofalse.

Incaseyouwanttomakeandapplicationwithmultipleforms,gotoyourproject,rightclickandaddanew“WindowsForm”.

Still,thefirstformthatwillopenisForm1so,ifyouwanttoopentheotherform,makeanewbutton,andonitsClickeventwrite:

private void button2_Click(object sender, EventArgs e) { Form2 NewForm = new Form2(); NewForm.Show(); }

Ofcourse,thisworksincaseyourformisnamed“Form2”andyoucannamethevariableafteritthewayyouwant.Thisisjustlikedeclaringaclass.

Toclosetheformyou’rein,type“Close();”,butthiswillalsocloseyourapplicationifyouareinyourmainform.Ifyoujustwanttohideit,use“Hide();”.

LabelsLabelsarejustpiecesoftextthatyouputonaformtoguidetheuser.Inyour“Calculator”project,drag3labelsonyourform.Fromthepropertywindowsyoucanchangetheircolor(ForeColor)theirtext(Text),theiralignment(TextAlign),font(Font),andmanymore…

CheckBoxAcheckboxisusuallyusedtocheckifanoptionisenabledornot.Inthiscasewecanuseittoenable/disablethe“Add”button.

Dragacheckboxonyourform.Thendouble‐clickonittoopenthefunctionthatoccurswhenit’scheckischangedandtype:

private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked == true) { button1.Enabled = true; } else

18 VISUALC#PROGRAMMINGBASICS

{ button1.Enabled = false; } }

Thiswilldisablethebuttonifitisuncheckedandenableitifitischecked.Asyoucansee,the“.checked”propertyisaBooleantypevariable.

ComboBoxesTheseareusuallyusedtoselectoneitemoracertainoption.Inthiscasewewilluseittochoosewhetherweaddormultiplythenumbers.Draganddropanewtextboxonyourform,andclickonthearrowintheupperrightcorner(thatisinsidearedsquareinthepicture)andclick“EditItems”:

Thenaddtheitemsyouwouldlikeinthewindowsthatopens.

Wecanuseitbycheckingifitsvalue(Textproperty)is“Add”or“Multiply”whenclickingthebutton:

private void button1_Click(object sender, EventArgs e) { double val1 = double.Parse(textBox1.Text); double val2 = double.Parse(textBox2.Text); if (comboBox1.Text == "Add") { textBox3.Text = Calc.AddNumbers(val1, val2).ToString(); } else { textBox3.Text = Calc.MultiplyNumbers(val1, val2).ToString(); } }

LinkLabelThelinklabelisbasicallyasimplelabelthatcanbeclickedjustlikeabutton.Themaindifferenceisthatthecursorchangeswhenyouhoveronitsotheuserknowsthatitcanbeclicked.

PictureBoxTochangethepictureofapicturebox,gotoitspropertiesin“Image”.Irecommendchangingit’sbackgroundimageinsteadoftherealimagethatit’sholdingsinceitcanbestretchedandtiled,butinthiscaseyoucoulduseapanelforthisjob.

RadioButtonsRadiobuttonsworkjustlikecheckboxes,butitdoesn’tallowyoutohavemorethanoneoptionselected.Fortunately,ifyouaddmoretotheform,onlyoneofthemcanbecheckedatonce.

Ifyouwantmoreradiobuttonsbutforsomethingdifferent,justmakeanewpanelandputthemintheresothattheywon’tun‐checkwhenyouclicktheotherbuttons.

VISUALC#PROGRAMMINGBASICS 19

ContentsGeneralRequirements...............................................................................................................................................................................................3

QuickStart–Yourfirstapplication .....................................................................................................................................................................3

Step1–Creatingtheproject .............................................................................................................................................................................3

Step2–Designingtheform ...............................................................................................................................................................................4

Step3–Debuggingtheapplication ................................................................................................................................................................6

Step4–Codingtheapplication ........................................................................................................................................................................6

Step5–Publishingyouapplication................................................................................................................................................................8

UnderstandingVisualC# .........................................................................................................................................................................................8

Controlnames ..........................................................................................................................................................................................................8

Eventsandclasses..................................................................................................................................................................................................9

SolutionsandProjects............................................................................................................................................................................................ 13

Filetypes ................................................................................................................................................................................................................. 13

Filesystem.............................................................................................................................................................................................................. 13

Otherprojecttypes .................................................................................................................................................................................................. 13

Windows.................................................................................................................................................................................................................. 13

Web............................................................................................................................................................................................................................ 14

Silverlight ................................................................................................................................................................................................................ 14

XNAGames ............................................................................................................................................................................................................. 14

SetupProjects ....................................................................................................................................................................................................... 14

VisualC#Syntax........................................................................................................................................................................................................ 15

Variables&Operations ..................................................................................................................................................................................... 15

Loops......................................................................................................................................................................................................................... 15

Decisions ................................................................................................................................................................................................................. 15

FileOperations ..................................................................................................................................................................................................... 16

WindowsFormsControls ..................................................................................................................................................................................... 17

Forms........................................................................................................................................................................................................................ 17

Labels........................................................................................................................................................................................................................ 17

CheckBox................................................................................................................................................................................................................ 17

ComboBoxes ......................................................................................................................................................................................................... 18

LinkLabel................................................................................................................................................................................................................ 18

PictureBox ............................................................................................................................................................................................................. 18

RadioButtons........................................................................................................................................................................................................ 18