Visual C-Sharp Programming Basics

download Visual C-Sharp Programming Basics

of 19

TAGS:

description

very important file

Transcript of Visual C-Sharp Programming Basics

  • ;

    InthistutorialyouwilllearnhowtomakeapplicationsforWindowsinC#.YouwilllearnhowtouseVisualStudiotobuildsimpleapplications,howtousemostoftheWindowsFormscontrols,andseveraltipsonhowtopublishyourapplication.

    MadebyDavideVitelaru

    VisualC#ProgrammingBasics

    http://davidevitelaru.com/

  • 2 VISUALC#PROGRAMMINGBASICS

  • VISUALC#PROGRAMMINGBASICS 3GeneralRequirementsTofollowthistutorialyouwillneedthefollowingitems:Knowingthebasicsofatleastoneprogramminglanguage(Toknowwhatvariables,arrays,functions,etcare)AcomputerrunningWindowsXP/Vista/7MicrosoftVisualC#Express(Clickfordownload)YoucanalsouseMicrosoftVisualStudioProfessional,butthisisacommercialversionoftheVisualC#Express,andithasmorefeatures.Wewillnotusemostoftheminthistutorialthough.Ifyouareinterestedinsomespecificpartofthistutorial,checkoutthetableofcontentsonthelastpagebecauseyoumightfindwhatyouarelookingfor.

    QuickStartYourfirstapplicationInthischapter,youwilllearnhowtomakeanapplicationinVisualStudiofromstarttofinish.Howtocodeit,designitandpublishit.Step1CreatingtheprojectTostart,openVisualC#ExpressorVisualStudioandcreateanewprojectbypressingontheNewProjecticonintheupperleftcorner.Inthewindowthatopensyoucanselectyourprojecttype,dependingonwhatyouwanttoprograminC#.TomakeasimpleWindowsapplication,selectWindowsFormsApplication,nameyourprojectCalculator(becausethisiswhatwearegoingtodo)andpressOK.

  • 4 VISUALC#PROGRAMMINGBASICSYounowcreatedanewproject.YoumightgetallscaredbyVisualC#sinterfacebecauseitisverycrowdedandyoudontknowwhatmostofthecontrolsdo.Letstakealookattheinterfaceforabit:thefirstthingthatpopsintoyoureyesistheformrightinthemiddle.ItisanemptyformandwhatyouhavetodoistotakecontrolsfromtheToolbox,thepanelfromtheleft,andputthemonit.

    YoucanseedifferenttypeofcontrolsintheToolbox:buttons,textboxes,progressbars,andyoucantakeallofthemandplacethemonyourform.Dontplaceanythingonyourformnow,ifyoudid,selectthemanddeletethem.OntherightyouhaveyourSolutionExplorer.Whenyoucreateanewproject,youautomaticallycreateanewsolution.Asolutionisacollectionofmultipleprojects,letssaywemakeanapplicationcalledCalculator(causethisiswhatweactuallydo),andCalculatorisanapplicationprojectinsidetheCalculatorsolution.IfwewanttocreateasetupforCalculator,wecreatethesetupprojectinsidethesamesolution.Youwilllearnwhateverythinginthesolutionexplorermeanslater.Step2DesigningtheformWhatwewanttocreateisasimplecalculatorapplication.Whatitwilldoistoaddtwonumbersinsertedbytheuser.Tostart,wewillneedthreetextboxes:Twoforthetwonumbersthattheuserwantstoaddandthethirdfortheresult.Wewillalsoneedabuttonsothattheusercanpressitandreceivehesresult.Todoallthis,clickontheTextBoxcontrolinthetoolbox,andthenclickonyourform.Asyoucansee,atextboxappearedonyourform.Repeatthisstepagainandcreatetwomoretextboxes.AlignthetextboxesthesamewayIdid:

  • VISUALC#PROGRAMMINGBASICS 5

    Now,selectthebuttoncontrolfromthetoolboxandcreateabuttonontheform.Good,wenowcreatedallthecontrolsweneedforourapplication.But,thereisaproblem,whyisthebuttonnamedButton1?Becausethisishowitisbydefault,tochangethat,weneedtochangeitsproperties.Bydefault,thepropertieswindowisnotopenedinVisualC#.Toopenit,gotoViewandclickonProperties.

    Thepropertiespanel(obviously)showstheselectcontrolsproperties,suchasheight,width,color,text,etcInthiscase,weonlyneedtochangethetextsincethebuttoncanberesizedwithusingthemouse.Clickonthebutton(Makesureyoudontdoubleclickit,oritscodewillopen.Ifthathappens,closethetabwiththecodefromthetopofthemiddlepanel).Onceclicked,thebuttonspropertieswillappearinthePropertieswindow.ScrolldownandgotoText.ToitsrightyouwillseeButton1.ChangethattoAdd,andpressenter.

  • 6 VISUALC#PROGRAMMINGBASICS YourbuttonnowhasAddwrittenonit.Verygood,thiswayyoucanediteveryitemsproperties,eventhetextboxes.Also,youmightnoticethattheformsnameisForm1.Trytodosomethingaboutit.HowTo:Clickonanemptyspaceontheform,changetheformstextpropertytoCalculator.

    Step3DebuggingtheapplicationOfcourse,weaddedthecontrolsonourform,butthebuttondoesntdoanythingsincewedidnttellitdotoanything.YoucanseeyourprogramrunningbypressingtheDebugbutton,thegreenarrowinthetoolbar( ).Whenyouclickthedebugbutton,youapplicationwillstart.Itshouldlooksomethinglikethis:

    Youprobablytriedtoclickthebuttonalready,andnoticedhowwellheisdoinghisjob.Debuggingisthebestmethodtotestyourapplicationbeforepublishingit.Everytimeyoumakeachangetoit,youdebugittoseeifitworked.Onceyoufinishtheapplication,youbuildtheentireprojectturningeverythingintooneexecutable,andprobablymakeasetupforyourapplication.Step4CodingtheapplicationTomaketheapplicationwork,youobviouslyhavetowritesomecode.Ifyouarestilldebuggingyourapplication,closeitandgobacktoyourproject.Now,doubleclickonyourbuttontoopenthecodewindow.Asyoucansee,everythingistabbedintheproject.Youcanalwaysgobacktotheformdesignerbyclickingitstabonthetop.

    Withalltheamountofcodethatyouhaveinfrontofyou,youmightgetscared(again!).Dontworryyouwillgetusedtoit,andtoevenmorethanthat.Ifyouarereadingthistutorial,letshopeyoualreadyknowthebasicsofanotherprogramminglanguage,ifnotitwillbehardforyoutosearchWikipediaforeverywordyoudontunderstand,butitwouldbeuseful.Thefirststatementsinthecodeimportsomeitemsfromthe.NETFramework.Whatisthatyoumightask,the.NETFrameworkisalargelibraryofcodedsolutionstocommonprogrammingproblemsthatmanagestheexecutionofprogramswrittenspecificallyfortheframework.Tobeclearer,itisalarge

  • VISUALC#PROGRAMMINGBASICS 7amountofcodealreadywrittenforyou,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;Byimportsomethingsfromthe.NETFramework,Imeantimportingsomeclasses.Thoseclassescanbetheforms,theusercontrols,andalltheotherthingsthathelpedusbynowcreatingtheprogram.Youwilllearnthemeaningofthemlater.Fornow,letsseetherestofthecode:namespace Calculator { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { } } }Thepublic Form1()statementisaclassthatisexecutedwhenwestarttheprogram;actually,whenweopentheformnamedForm1.cs(.csisfromCSharp).Incaseyoudidnotknow,inC#thecodeisusuallyputbetweencurlybracesjustlikeinJavaandC++.Theprivate 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.

    Step5PublishingyouapplicationWhatyouhavetodoistocreateaniconforyourapplication,changeitspublishingsettingsandmakeasetupforit,butwewillskipthesestepsastheyarenotrelatedtobasicC#programming.Note:CheckouttheAdvancedVisualC#Programmingtutorialonceyoufinishthisone.

    UnderstandingVisualC#Great,nowthatyoumadeyourfirstapplicationyoucangoevendeeperintoC#andunderstandhowmostthingswork,andsomeextrathingsthatwillmakeyourapplicationworkbetter.ControlnamesFirstofall,oneimportantthingthatyouhavetoknowisthateveryitemonyourformhasaname.AndIamnottalkingaboutTextBoxorButton,butabouttheirNameproperty.

  • VISUALC#PROGRAMMINGBASICS 9Gobacktoyourformsdesignerandclickonthefirsttextbox.Inthepropertywindow,youwillseethatitsnamepropertyistextBox1.Inourpreviouscode,wetookthevaluefromthistextboxbythefollowingmethod: val1 = Double.Parse(textBox1.Text);Howdoesthiswork?Letsforgetabouttheconversionforafewseconds,andseewhatweactuallyassignedtothevariable(consideringthatthetextboxalreadyholdsadoublevalue). val1 = textBox1.Text;Weassignedthespecificpropertyofacontroltoavariable.Thecorrectsyntaxis: variable = control.property; Thisishowitalwaysworks.Ofcourse,wecandotheexactoppositeandassigntothecontrolspropertyacertainvariablejustlikewedidearlier: textBox3.Text = (val1 + val2).ToString();Thenamesareusedtodistinguishbetweenthecontrolsontheform.Youcandothesamethingwithbuttons,justclickonabutton,andchangeitsnameproperty.Itisrecommendedthatyourenameyourbuttonssothatyouknowwhateachofthemdoes.EventsandclassesWhenyoudoubleclickabutton,youareautomaticallyredirectedtoyourcodewhereanewfunctionappears.Thatfunctionwillbeexecutedwhenyouclickthebutton.Youcanrunanyotherfunctionwhenyouclickthebutton,allyouhavetodochangetheeventthatoccurswhenyouclickit.Todothat,gotoitspropertywindow,andclickontheEventsbutton( ).Ontheleftsideofthetablethatjustappearedbellowyouwillseetheevents,andontherightsideyouwillseewhathappens(Whatfunctionisexecuted)whenthateventoccurs.Asyoucansee,whenweClickthebutton,thebutton1_Clickfunctionisexecuted.Thatfunctionhasbeenautomaticallywrittenforyouwhenyoudoubleclickthebutton.Ofcourse,thesamefunctioncanbeexecutednomatterwhateventoccurs,forexample,gototheMouseHoverevent,andtypebutton1_Clicktoitsleft.Fromnow,youdonthavetoclickthebutton,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;returnisusedtospecifywhatvaluethefunctionwillreturnwhenitiscalled.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

    224

    button1_ClickFunctionisexecuted:val1val2

    AddNumbers(val1,val2)returnval1+val2

  • VISUALC#PROGRAMMINGBASICS 11Notehowthebutton1_ClickfunctionpassesthevaluestotheAddNumbersandthenassignsthemtothethirdtextbox.Debugyourapplicationandyouwillnoticethatitwillwork.Thebestpartinusingfunctiontodoyourjobisthatyoucanusethemmultipletimeswithoutyouhavingtowritethesamecodealloveragain.Ifyouhavetoomanyfunctions,yousourcecodemightgetreallycrowded.Inthiscaseyoumightwanttocreateaclasstoholdalloftheminoneplace.Tocreateaclassinyourproject,rightclickonyourprojecticonintheSolutionExplorerandaddanewclass:

    NameitCalculator.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) Wetypedpublicbeforedeclaringthefunctionsowecanuseitoutsidethisclass.Now,gobacktoForm1.csanddeclaretheclassrightontopoftheMainfunction: Calculator Calc = new Calculator();

  • 12 VISUALC#PROGRAMMINGBASICSThecorrectsyntaxis: ClassName WhatNameYouWantToUse = new ClassName();Nowthatwedeclaredtheclass,weneedtousethefunctionfromitnamedAddNumbers.Todothat,changethefollowinglineofthebutton1_Clickfunction: textBox3.Text = Calc.AddNumbers(val1, val2).ToString(); Thisway,youcanusetheclassonmultipleforms.Homework:MakeanewbuttonandanewfunctionnamedMultiplyNumbers,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 13SolutionsandProjectsItistimetolearnhowthesolutionexplorerworks.FiletypesAllyouhavetocareaboutinthesolutionexploreraretheforms,classesandreferences.Theformshavethefollowingicon: andtheyareactuallyacollectionoftwoclasses,onehandlesthedesignbutyoudontwriteinthatfile,insteadyouarrangethecontrolusingthedesignerthatwritesthecodebyitselfinthedesignerclass,andtheotheroneisthecodeclass.Rightclickingontheformiconwillgiveyoutheoptiontoopeneitherthecodeorthedesigner.Theclasseshavethefollowingicon: andtheyarejustindependentfileswithcode.Programsisthemainclassofyourproject,andyoumustnotmodifyit.Thereferencesareallinsidethisfolder: ,andtheyusuallyrepresentthepiecesofthe.NETFrameworkthatyouareusing.Also,ifyouareusinganyotherclasslibraryitwillappearthere.Resourcesusuallyrepresenttheimagesthatyouimportedintoyourproject.Theycanbefoundallinthisfolder: .FilesystemYoumightaskyourselfafteryouworkatanapplicationWhereexactlyismyapplication?.Tofindtheexecutablecreatedasaresultofyoubuildingyourproject,gotoyourdocumentsfolders,inVisualStudio2008(Dependingontheversionyouhave)andgoto:Projects///bin/Debug/.exeOtherprojecttypesThischapterisnotthatimportantandyoucanskipitifyouarenotinterestedinothertypesofprojects.WindowsAsyouhavenoticedwhenyoucreatedanewproject,therearemanyothertypesofprojects.ThisiswhatwehaveintheWindowscategory:

    TheWindowsFormsApplicationprojectiswhatwepreviouslymade.Itisjustasimpleapplicationwithauserinterface.Ontheotherhand,theConsoleApplicationisasimpleC#applicationprojectwithouttheuserinterface,itworksinsidetheconsole.

  • 14 VISUALC#PROGRAMMINGBASICSTheClassLibraryisactuallyaprojectfullofclasses.Onceyoucompiletheproject,youwillendupwitha.DLLfile(DynamicLinkLibrary).Youcanaddthatfileasareferencetoyourprojectsoyoucanusetheclassesinsidethelibrary.Theotherprojecttypesareadvancedandyouwilllearnwhattheyaregoodforattherighttime.WebTherearealsoothercategoriesofVisualC#projecttypes:WebprojectsTheseareforASP.NETWebDevelopers:

    SilverlightSilverlightdevelopmentIncaseyouwanttoprogramSilverlightapplications:

    XNAGamesAlso,lastbutnotleast,XNAprojectsforgamemakingusingC#:

    Forthelasttwoprojectcategoriesyoumustinstallplugins.Dontworry,theyarefreetodownloadfromtheinternet,howyouwilllearntousethemisthebiggestproblem.SetupProjectsIncaseyouhaveVisualStudioProfessionalinstalled,underOtherProjectTypesinSetupandDeploymentyouhavethis:

    Thesetupprojectistheeasiestwaytocreateadecentandcustomizablesetupforyourproject.

  • VISUALC#PROGRAMMINGBASICS 15VisualC#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
  • 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 17WindowsFormsControlsInthischapteryouwilllearnhowtousemostofthecontrolsthatyoucanfindinyourtoolbox.Wearestillgoingtoworkonthecalculatorprojectuntilwereachsomecontrolthatwecantuseinsuchaproject.Also,keepinmindthatyouwilllearntousesomeeasycontrolinthischapter,formoredifficultcontrols,seetheAdvancedVisualC#Programmingtutorial.FormsThisisamustreaditembecauseyouwillneedtoknowhowtomakeyourformlookbetter.Forstart,ourmainformincalculatornamedForm1isresizable,evenifithasonly4controlsinit.Onceyouresizeit,itlooksuglysogotoitspropertiesinFormBorderStyleandchangeittoFixedSingle.Thiswayyoucantresizeitanymore.Eventhoughyoucantresizeit,youcanstillmaximizeit(annoying,isntit?)sogotoitsMaximizeBoxpropertyandchangethattoofalse.Incaseyouwanttomakeandapplicationwithmultipleforms,gotoyourproject,rightclickandaddanewWindowsForm.Still,thefirstformthatwillopenisForm1so,ifyouwanttoopentheotherform,makeanewbutton,andonitsClickeventwrite: private void button2_Click(object sender, EventArgs e) { Form2 NewForm = new Form2(); NewForm.Show(); }Ofcourse,thisworksincaseyourformisnamedForm2andyoucannamethevariableafteritthewayyouwant.Thisisjustlikedeclaringaclass.Toclosetheformyourein,typeClose();,butthiswillalsocloseyourapplicationifyouareinyourmainform.Ifyoujustwanttohideit,useHide();.LabelsLabelsarejustpiecesoftextthatyouputonaformtoguidetheuser.InyourCalculatorproject,drag3labelsonyourform.Fromthepropertywindowsyoucanchangetheircolor(ForeColor)theirtext(Text),theiralignment(TextAlign),font(Font),andmanymoreCheckBoxAcheckboxisusuallyusedtocheckifanoptionisenabledornot.Inthiscasewecanuseittoenable/disabletheAddbutton.Dragacheckboxonyourform.Thendoubleclickonittoopenthefunctionthatoccurswhenitscheckischangedandtype: 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.checkedpropertyisaBooleantypevariable.ComboBoxesTheseareusuallyusedtoselectoneitemoracertainoption.Inthiscasewewilluseittochoosewhetherweaddormultiplythenumbers.Draganddropanewtextboxonyourform,andclickonthearrowintheupperrightcorner(thatisinsidearedsquareinthepicture)andclickEditItems:

    Thenaddtheitemsyouwouldlikeinthewindowsthatopens.Wecanuseitbycheckingifitsvalue(Textproperty)isAddorMultiplywhenclickingthebutton: 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,gotoitspropertiesinImage.Irecommendchangingitsbackgroundimageinsteadoftherealimagethatitsholdingsinceitcanbestretchedandtiled,butinthiscaseyoucoulduseapanelforthisjob.RadioButtonsRadiobuttonsworkjustlikecheckboxes,butitdoesntallowyoutohavemorethanoneoptionselected.Fortunately,ifyouaddmoretotheform,onlyoneofthemcanbecheckedatonce.Ifyouwantmoreradiobuttonsbutforsomethingdifferent,justmakeanewpanelandputthemintheresothattheywontuncheckwhenyouclicktheotherbuttons.

  • VISUALC#PROGRAMMINGBASICS 19ContentsGeneralRequirements...............................................................................................................................................................................................3QuickStartYourfirstapplication .....................................................................................................................................................................3Step1Creatingtheproject .............................................................................................................................................................................3Step2Designingtheform ...............................................................................................................................................................................4Step3Debuggingtheapplication ................................................................................................................................................................6Step4Codingtheapplication ........................................................................................................................................................................6Step5Publishingyouapplication................................................................................................................................................................8UnderstandingVisualC# .........................................................................................................................................................................................8Controlnames ..........................................................................................................................................................................................................8Eventsandclasses..................................................................................................................................................................................................9SolutionsandProjects............................................................................................................................................................................................ 13Filetypes ................................................................................................................................................................................................................. 13Filesystem.............................................................................................................................................................................................................. 13Otherprojecttypes .................................................................................................................................................................................................. 13Windows.................................................................................................................................................................................................................. 13Web............................................................................................................................................................................................................................ 14Silverlight ................................................................................................................................................................................................................ 14XNAGames ............................................................................................................................................................................................................. 14SetupProjects ....................................................................................................................................................................................................... 14VisualC#Syntax........................................................................................................................................................................................................ 15Variables&Operations ..................................................................................................................................................................................... 15Loops......................................................................................................................................................................................................................... 15Decisions ................................................................................................................................................................................................................. 15FileOperations ..................................................................................................................................................................................................... 16WindowsFormsControls ..................................................................................................................................................................................... 17Forms........................................................................................................................................................................................................................ 17Labels........................................................................................................................................................................................................................ 17CheckBox................................................................................................................................................................................................................ 17ComboBoxes ......................................................................................................................................................................................................... 18LinkLabel................................................................................................................................................................................................................ 18PictureBox ............................................................................................................................................................................................................. 18RadioButtons........................................................................................................................................................................................................ 18