You are on page 1of 19

;

VisualC#ProgrammingBasics

InthistutorialyouwilllearnhowtomakeapplicationsforWindowsinC#.Youwilllearnhow
touseVisualStudiotobuildsimpleapplications,howtousemostoftheWindowsForms
controls,andseveraltipsonhowtopublishyourapplication.

MadebyDavideVitelaru

http://davidevitelaru.com/

VISUALC#PROGRAMMINGBASICS

VISUALC#PROGRAMMINGBASICS 3

GeneralRequirements

Tofollowthistutorialyouwillneedthefollowingitems:
Knowingthebasicsofatleastoneprogramminglanguage(Toknowwhatvariables,
arrays,functions,etcare)
AcomputerrunningWindowsXP/Vista/7
MicrosoftVisualC#Express(Clickfordownload)
YoucanalsouseMicrosoftVisualStudioProfessional,butthisisacommercialversionoftheVisualC#
Express,andithasmorefeatures.Wewillnotusemostoftheminthistutorialthough.

Ifyouareinterestedinsomespecificpartofthistutorial,checkoutthetableofcontentson
thelastpagebecauseyoumightfindwhatyouarelookingfor.

QuickStartYourfirstapplication
Inthischapter,youwilllearnhowtomakeanapplicationinVisualStudiofromstarttofinish.Howtocode
it,designitandpublishit.

Step1Creatingtheproject
Tostart,openVisualC#ExpressorVisualStudioandcreateanewprojectbypressingontheNew
Projecticonintheupperleftcorner.
Inthewindowthatopensyoucanselectyourprojecttype,dependingonwhatyouwanttoprograminC#.
TomakeasimpleWindowsapplication,selectWindowsFormsApplication,nameyourproject
Calculator(becausethisiswhatwearegoingtodo)andpressOK.

VISUALC#PROGRAMMINGBASICS

Younowcreatedanewproject.YoumightgetallscaredbyVisualC#sinterfacebecauseitisvery
crowdedandyoudontknowwhatmostofthecontrolsdo.Letstakealookattheinterfaceforabit:the
firstthingthatpopsintoyoureyesistheformrightinthemiddle.Itisanemptyformandwhatyouhave
todoistotakecontrolsfromtheToolbox,thepanelfromtheleft,andputthemonit.

YoucanseedifferenttypeofcontrolsintheToolbox:buttons,textboxes,progressbars,andyoucantake
allofthemandplacethemonyourform.Dontplaceanythingonyourformnow,ifyoudid,selectthem
anddeletethem.
OntherightyouhaveyourSolutionExplorer.Whenyoucreateanewproject,youautomaticallycreatea
newsolution.Asolutionisacollectionofmultipleprojects,letssaywemakeanapplicationcalled
Calculator(causethisiswhatweactuallydo),andCalculatorisanapplicationprojectinsidethe
Calculatorsolution.IfwewanttocreateasetupforCalculator,wecreatethesetupprojectinsidethe
samesolution.Youwilllearnwhateverythinginthesolutionexplorermeanslater.

Step2Designingtheform

Whatwewanttocreateisasimplecalculatorapplication.Whatitwilldoistoaddtwonumbersinserted
bytheuser.Tostart,wewillneedthreetextboxes:Twoforthetwonumbersthattheuserwantstoadd
andthethirdfortheresult.Wewillalsoneedabuttonsothattheusercanpressitandreceivehesresult.
Todoallthis,clickontheTextBoxcontrolinthetoolbox,andthenclickonyourform.Asyoucansee,a
textboxappearedonyourform.Repeatthisstepagainandcreatetwomoretextboxes.Alignthetext
boxesthesamewayIdid:

VISUALC#PROGRAMMINGBASICS 5

Now,selectthebuttoncontrolfromthetoolboxandcreateabuttonontheform.
Good,wenowcreatedallthecontrolsweneedforourapplication.But,thereisaproblem,whyisthe
buttonnamedButton1?Becausethisishowitisbydefault,tochangethat,weneedtochangeits
properties.Bydefault,thepropertieswindowisnotopenedinVisualC#.Toopenit,gotoViewandclick
onProperties.

Thepropertiespanel(obviously)showstheselectcontrolsproperties,suchasheight,width,color,text,
etcInthiscase,weonlyneedtochangethetextsincethebuttoncanberesizedwithusingthemouse.
Clickonthebutton(Makesureyoudontdoubleclickit,oritscodewillopen.Ifthathappens,closethetab
withthecodefromthetopofthemiddlepanel).Onceclicked,thebuttonspropertieswillappearinthe
Propertieswindow.ScrolldownandgotoText.ToitsrightyouwillseeButton1.Changethatto
Add,andpressenter.

VISUALC#PROGRAMMINGBASICS

YourbuttonnowhasAddwrittenonit.Verygood,thiswayyoucanediteveryitemsproperties,even
thetextboxes.
Also,youmightnoticethattheformsnameisForm1.Trytodosomethingaboutit.
HowTo:Clickonanemptyspaceontheform,changetheformstextpropertytoCalculator.

Step3Debuggingtheapplication

Ofcourse,weaddedthecontrolsonourform,butthebuttondoesntdoanythingsincewedidnttellit
dotoanything.YoucanseeyourprogramrunningbypressingtheDebugbutton,thegreenarrowinthe
toolbar( ).Whenyouclickthedebugbutton,youapplicationwillstart.Itshouldlooksomethinglike
this:

Youprobablytriedtoclickthebuttonalready,andnoticedhowwellheisdoinghisjob.Debuggingisthe
bestmethodtotestyourapplicationbeforepublishingit.Everytimeyoumakeachangetoit,youdebugit
toseeifitworked.Onceyoufinishtheapplication,youbuildtheentireprojectturningeverythingintoone
executable,andprobablymakeasetupforyourapplication.

Step4Codingtheapplication

Tomaketheapplicationwork,youobviouslyhavetowritesomecode.Ifyouarestilldebuggingyour
application,closeitandgobacktoyourproject.Now,doubleclickonyourbuttontoopenthecode
window.Asyoucansee,everythingistabbedintheproject.Youcanalwaysgobacktotheformdesigner
byclickingitstabonthetop.

Withalltheamountofcodethatyouhaveinfrontofyou,youmightgetscared(again!).Dontworryyou
willgetusedtoit,andtoevenmorethanthat.Ifyouarereadingthistutorial,letshopeyoualreadyknow
thebasicsofanotherprogramminglanguage,ifnotitwillbehardforyoutosearchWikipediaforevery
wordyoudontunderstand,butitwouldbeuseful.
Thefirststatementsinthecodeimportsomeitemsfromthe.NETFramework.Whatisthatyoumightask,
the.NETFrameworkisalargelibraryofcodedsolutionstocommonprogrammingproblemsthat
managestheexecutionofprogramswrittenspecificallyfortheframework.Tobeclearer,itisalarge

VISUALC#PROGRAMMINGBASICS 7

amountofcodealreadywrittenforyou,soyoucanbuildprogramswithaprettyuserinterfaceandother
things.Ithelpsyouverymuchbecauseitreducestheamountofthingsthatyouneedtolearntocreatethe
entireuserinterface.WeshouldallthankMicrosoftforit:
using
using
using
using
using
using
using
using

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

Byimportsomethingsfromthe.NETFramework,Imeantimportingsomeclasses.Thoseclassescanbe
theforms,theusercontrols,andalltheotherthingsthathelpedusbynowcreatingtheprogram.Youwill
learnthemeaningofthemlater.
Fornow,letsseetherestofthecode:
namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
}
}

Thepublic Form1()statementisaclassthatisexecutedwhenwestarttheprogram;actually,whenwe
opentheformnamedForm1.cs(.csisfromCSharp).Incaseyoudidnotknow,inC#thecodeis
usuallyputbetweencurlybracesjustlikeinJavaandC++.
Theprivate void button1_Click(object sender, EventArgs e)isthatclassthatisexecutedwhen
weclickthebutton.Insideit,wewillwritethecodethatwilladdthetwovaluesfromthetextboxes.
Note:InC#,twoslashes(//)representsthebeginningofacomment.Acommentisapieceofcodethatisnot
executedbythecompiler,itisusedtohelpyouorganizeyoucode,andsothatotherprogrammerswill
understandwhateverypieceofcodemeans.Wewillusecommentsinsideourcodesforbetterexplanation.
Tomakethatbuttonaddthetwovaluesandreturnthesumweneed,wehavetograbthetextcontent
fromthetwotextboxes,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".

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;wedeclaredtwovariablesandassignedthevaluesofthetwotextboxes
afterweconvertedthemfromstringstointegers.Then,wechangedthetextofthethirdtextboxintothe
sumofthetwovariables,andweconvertedittoastringinthesametime.Andwedidallofthisattheclick
ofabutton.

Step5Publishingyouapplication

Whatyouhavetodoistocreateaniconforyourapplication,changeitspublishingsettingsandmakea
setupforit,butwewillskipthesestepsastheyarenotrelatedtobasicC#programming.
Note:CheckouttheAdvancedVisualC#Programmingtutorialonceyoufinishthisone.

UnderstandingVisualC#
Great,nowthatyoumadeyourfirstapplicationyoucangoevendeeperintoC#andunderstandhowmost
thingswork,andsomeextrathingsthatwillmakeyourapplicationworkbetter.

Controlnames
Firstofall,oneimportantthingthatyouhavetoknowisthateveryitemonyourformhasaname.AndI
amnottalkingaboutTextBoxorButton,butabouttheirNameproperty.

VISUALC#PROGRAMMINGBASICS 9

Gobacktoyourformsdesignerandclickonthefirsttextbox.Inthepropertywindow,youwillseethatits
namepropertyistextBox1.Inourpreviouscode,wetookthevaluefromthistextboxbythefollowing
method:
val1 = Double.Parse(textBox1.Text);

Howdoesthiswork?Letsforgetabouttheconversionforafewseconds,andseewhatweactually
assignedtothevariable(consideringthatthetextboxalreadyholdsadoublevalue).
val1 = textBox1.Text;

Weassignedthespecificpropertyofacontroltoavariable.Thecorrectsyntaxis:
variable = control.property;

Thisishowitalwaysworks.Ofcourse,wecandotheexactoppositeandassigntothecontrolspropertya
certainvariablejustlikewedidearlier:
textBox3.Text = (val1 + val2).ToString();

Thenamesareusedtodistinguishbetweenthecontrolsontheform.
Youcandothesamethingwithbuttons,justclickonabutton,andchangeitsnameproperty.Itis
recommendedthatyourenameyourbuttonssothatyouknowwhateachofthemdoes.

Eventsandclasses
Whenyoudoubleclickabutton,youareautomaticallyredirectedtoyourcodewhereanewfunction
appears.Thatfunctionwillbeexecutedwhenyouclickthebutton.Youcanrunanyotherfunctionwhen
youclickthebutton,allyouhavetodochangetheeventthatoccurswhenyouclickit.Todothat,gotoits
propertywindow,andclickontheEventsbutton(
).Ontheleftsideofthetablethatjustappeared
bellowyouwillseetheevents,andontherightsideyouwillseewhathappens(Whatfunctionis
executed)whenthateventoccurs.
Asyoucansee,whenweClickthebutton,thebutton1_Clickfunctionisexecuted.Thatfunctionhasbeen
automaticallywrittenforyouwhenyoudoubleclickthebutton.Ofcourse,thesamefunctioncanbe
executednomatterwhateventoccurs,forexample,gototheMouseHoverevent,andtypebutton1_Click
toitsleft.Fromnow,youdonthavetoclickthebutton,allyouhavetodoisplacethecursoraboveitand
thebutton1_Clickfunctionwillrun,addingthetwonumbers.
Youcanalsodeclareanewfunctiontodothejob,andcallitwhenyouclickthebutton.Typesomewhere
belowthebutton1_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,delete
thecodeinthebutton1_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.WeusedtheAddNumbersfunction
toaddthetwonumbers.

Howdoesthiswork?

button1_ClickFunctionis

Form1
executed:

Buttonisclicked

AddNumbers(val1,val2)

returnval1+val2

val1
val2

VISUALC#PROGRAMMINGBASICS 11

Notehowthebutton1_ClickfunctionpassesthevaluestotheAddNumbersandthenassignsthemtothe
thirdtextbox.
Debugyourapplicationandyouwillnoticethatitwillwork.Thebestpartinusingfunctiontodoyourjob
isthatyoucanusethemmultipletimeswithoutyouhavingtowritethesamecodealloveragain.
Ifyouhavetoomanyfunctions,yousourcecodemightgetreallycrowded.Inthiscaseyoumightwantto
createaclasstoholdalloftheminoneplace.
Tocreateaclassinyourproject,rightclickonyourprojecticonintheSolutionExplorerandaddanew
class:

NameitCalculator.cs.Onceyoucreateit,itwillappearinthesolutionexplorer,itwillautomatically
open,andyouwillhavethis:
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
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#PROGRAMMINGBASICS

Thecorrectsyntaxis:
ClassName WhatNameYouWantToUse = new ClassName();

Nowthatwedeclaredtheclass,weneedtousethefunctionfromitnamedAddNumbers.Todothat,
changethefollowinglineofthebutton1_Clickfunction:
textBox3.Text = Calc.AddNumbers(val1, val2).ToString();

Thisway,youcanusetheclassonmultipleforms.
Homework:MakeanewbuttonandanewfunctionnamedMultiplyNumbers,andmakeitmultiplythetwo
numberswhenthebuttonispressed.
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

SolutionsandProjects

Itistimetolearnhowthesolutionexplorerworks.

Filetypes

Allyouhavetocareaboutinthesolutionexploreraretheforms,
classesandreferences.
Theformshavethefollowingicon:
andtheyareactuallya
collectionoftwoclasses,onehandlesthedesignbutyoudont
writeinthatfile,insteadyouarrangethecontrolusingthe
designerthatwritesthecodebyitselfinthedesignerclass,and
theotheroneisthecodeclass.Rightclickingontheformicon
willgiveyoutheoptiontoopeneitherthecodeorthedesigner.
Theclasseshavethefollowingicon: andtheyarejust
independentfileswithcode.Programsisthemainclassof
yourproject,andyoumustnotmodifyit.
Thereferencesareallinsidethisfolder: ,andtheyusuallyrepresentthepiecesofthe.NET
Frameworkthatyouareusing.Also,ifyouareusinganyotherclasslibraryitwillappearthere.
Resourcesusuallyrepresenttheimagesthatyouimportedintoyourproject.Theycanbefoundallinthis
folder: .

Filesystem

YoumightaskyourselfafteryouworkatanapplicationWhereexactlyismyapplication?.Tofindthe
executablecreatedasaresultofyoubuildingyourproject,gotoyourdocumentsfolders,inVisualStudio
2008(Dependingontheversionyouhave)andgoto:
Projects/<ProjectName>/<ProjectName>/bin/Debug/<ProjectName>.exe

Otherprojecttypes

Thischapterisnotthatimportantandyoucanskipitifyouarenotinterestedinothertypesofprojects.

Windows

Asyouhavenoticedwhenyoucreatedanewproject,therearemanyothertypesofprojects.Thisiswhat
wehaveintheWindowscategory:

TheWindowsFormsApplicationprojectiswhatwepreviouslymade.Itisjustasimpleapplicationwith
auserinterface.Ontheotherhand,theConsoleApplicationisasimpleC#applicationprojectwithout
theuserinterface,itworksinsidetheconsole.

14

VISUALC#PROGRAMMINGBASICS

TheClassLibraryisactuallyaprojectfullofclasses.Onceyoucompiletheproject,youwillendupwitha
.DLLfile(DynamicLinkLibrary).Youcanaddthatfileasareferencetoyourprojectsoyoucanusethe
classesinsidethelibrary.
Theotherprojecttypesareadvancedandyouwilllearnwhattheyaregoodforattherighttime.

Web

TherearealsoothercategoriesofVisualC#projecttypes:
WebprojectsTheseareforASP.NETWebDevelopers:

Silverlight

SilverlightdevelopmentIncaseyouwanttoprogramSilverlightapplications:

XNAGames

Also,lastbutnotleast,XNAprojectsforgamemakingusingC#:

Forthelasttwoprojectcategoriesyoumustinstallplugins.Dontworry,theyarefreetodownloadfrom
theinternet,howyouwilllearntousethemisthebiggestproblem.

SetupProjects

IncaseyouhaveVisualStudioProfessionalinstalled,underOtherProjectTypesinSetupand
Deploymentyouhavethis:

Thesetupprojectistheeasiestwaytocreateadecentandcustomizablesetupforyourproject.

VISUALC#PROGRAMMINGBASICS 15

VisualC#Syntax

ThischapterwillshowyousomebasicC#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;
}

FileOperations
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
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

WindowsFormsControls
Inthischapteryouwilllearnhowtousemostofthecontrolsthatyoucanfindinyourtoolbox.Wearestill
goingtoworkonthecalculatorprojectuntilwereachsomecontrolthatwecantuseinsuchaproject.
Also,keepinmindthatyouwilllearntousesomeeasycontrolinthischapter,formoredifficultcontrols,
seetheAdvancedVisualC#Programmingtutorial.

Forms

Thisisamustreaditembecauseyouwillneedtoknowhowtomakeyourformlookbetter.Forstart,our
mainformincalculatornamedForm1isresizable,evenifithasonly4controlsinit.Onceyouresizeit,it
looksuglysogotoitspropertiesinFormBorderStyleandchangeittoFixedSingle.Thiswayyoucant
resizeitanymore.
Eventhoughyoucantresizeit,youcanstillmaximizeit(annoying,isntit?)sogotoitsMaximizeBox
propertyandchangethattoofalse.
Incaseyouwanttomakeandapplicationwithmultipleforms,gotoyourproject,rightclickandadda
newWindowsForm.
Still,thefirstformthatwillopenisForm1so,ifyouwanttoopentheotherform,makeanewbutton,and
onitsClickeventwrite:
private void button2_Click(object sender, EventArgs e)
{
Form2 NewForm = new Form2();
NewForm.Show();
}

Ofcourse,thisworksincaseyourformisnamedForm2andyoucannamethevariableafterittheway
youwant.Thisisjustlikedeclaringaclass.
Toclosetheformyourein,typeClose();,butthiswillalsocloseyourapplicationifyouareinyour
mainform.Ifyoujustwanttohideit,useHide();.

Labels

Labelsarejustpiecesoftextthatyouputonaformtoguidetheuser.InyourCalculatorproject,drag3
labelsonyourform.Fromthepropertywindowsyoucanchangetheircolor(ForeColor)theirtext(Text),
theiralignment(TextAlign),font(Font),andmanymore

CheckBox

Acheckboxisusuallyusedtocheckifanoptionisenabledornot.Inthiscasewecanuseitto
enable/disabletheAddbutton.
Dragacheckboxonyourform.Thendoubleclickonittoopenthefunctionthatoccurswhenitscheckis
changedandtype:
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.

ComboBoxes

Theseareusuallyusedtoselectoneitemoracertainoption.Inthiscasewewilluseittochoosewhether
weaddormultiplythenumbers.Draganddropanewtextboxonyourform,andclickonthearrowinthe
upperrightcorner(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();
}

LinkLabel

Thelinklabelisbasicallyasimplelabelthatcanbeclickedjustlikeabutton.Themaindifferenceisthat
thecursorchangeswhenyouhoveronitsotheuserknowsthatitcanbeclicked.

PictureBox

Tochangethepictureofapicturebox,gotoitspropertiesinImage.Irecommendchangingits
backgroundimageinsteadoftherealimagethatitsholdingsinceitcanbestretchedandtiled,butinthis
caseyoucoulduseapanelforthisjob.

RadioButtons

Radiobuttonsworkjustlikecheckboxes,butitdoesntallowyoutohavemorethanoneoptionselected.
Fortunately,ifyouaddmoretotheform,onlyoneofthemcanbecheckedatonce.
Ifyouwantmoreradiobuttonsbutforsomethingdifferent,justmakeanewpanelandputtheminthere
sothattheywontuncheckwhenyouclicktheotherbuttons.

VISUALC#PROGRAMMINGBASICS 19

Contents
GeneralRequirements............................................................................................................................................................................................... 3
QuickStartYourfirstapplication ..................................................................................................................................................................... 3
Step1Creatingtheproject ............................................................................................................................................................................. 3
Step2Designingtheform ............................................................................................................................................................................... 4
Step3Debuggingtheapplication ................................................................................................................................................................ 6
Step4Codingtheapplication ........................................................................................................................................................................ 6
Step5Publishingyouapplication................................................................................................................................................................ 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

You might also like