Tải bản đầy đủ - 0 (trang)
Chapter 6: Introducing Windows Applications and ADO.NET

Chapter 6: Introducing Windows Applications and ADO.NET

Tải bản đầy đủ - 0trang

Overview

Inthepreviouschapters,youranprogramsusingtheWindows

CommandPrompttool.Inthischapter,you'llbeintroducedtoWindows

applications.Windowsprovidesgraphicalitems,suchasmenus,text

boxes,andradiobuttons,sothatyoucanbuildavisualinterfacethatis

easytouse.YoucancreateWindowsapplicationsthatuseADO.NET,

andyou'llseehowtodothat,usingVisualStudio.NET(VS.NET),inthis

chapter.

Windowsapplicationsaresimpletolearnandusebecausepeoplehave

becomeaccustomedtointeractingwithmachinesinavisualmanner.The

ubiquitousMicrosoftWordandExcelarejusttwoexamplesofhow

successfulWindowsapplicationscanbebecauseofthewaythey

combinepowerandeaseofuse.

Theideaofusinggraphicaluserinterfaces(GUIs)andamouseto

interactwithacomputerisnotuniquetoWindows.Infact,these

conceptswereoriginallydevelopedbackintheearly1970sbyengineers

atXeroxCorporation'sPaloAltoResearchCenter(PARC)inCalifornia,

andoneofthefirstcomputerstouseaGUIandamousewastheAlto.

Unfortunately,theAltowasexpensive,anditwasn'tuntilAppleComputer

launchedtheMacintoshin1984thattheGUIbecamepopular.Later,

MicrosoftdevelopedtheWindowsoperatingsystemthatbuiltonthe

ideasmadepopularbyApple.

Featuredinthischapter:

DevelopingasimpleWindowsapplication

UsingWindowscontrols

AccessingadatabasewithaDataGridcontrol

CreatingaWindowsformwiththeDataFormWizard



DevelopingaSimpleWindowsApplication

Inthissection,you'llseehowtocreateasimpleWindowsapplication

usingVS.NET.Thisapplicationwillconsistofasingleformthatcontains

alabelandabutton.Whenyouclickthebutton,thetextforthelabelwill

changetoaquotefromShakespeare'splay,Macbeth.You'llalsosee

howtocompileandruntheexampleapplication.



CreatingtheWindowsApplication

StartVS.NETbyselectingStart➣Programs➣MicrosoftVisualStudio

.NET➣MicrosoftVisualStudio.NET.TocreateanewWindows

application,clicktheNewProjectbuttonontheStartpage,orselectFile

➣New➣Project.

Tip YoucanalsocreateanewprojectbypressingCtrl+Shift+Non

yourkeyboard.

You'llseetheNewProjectdialogbox,whichyouusetoselectthetypeof

projectyouwanttocreate.Becauseyou'regoingtocreateaC#Windows

application,selecttheVisualC#ProjectsfolderfromtheProjectTypes

list,andselectWindowsApplicationfromtheTemplatesareaoftheNew

Projectdialogbox.VS.NETwillassignadefaultnametoyourproject;

thisdefaultnamewillbeWindowsApplication1,orsomethingsimilar.

Youcanspecifyyourownnameforyourprojectbychangingthetextin

theNamefield;goaheadandenterMyWindowsApplicationinthe

Namefield,asshowninFigure6.1.



Figure6.1:CreatingaC#

WindowsapplicationinVisualStudio.NET

Note TheLocationfieldspecifiesthedirectorywherethefilesfor

yournewprojectarestored.VS.NETwillsetadefault

directory,butyoucanchangethisbyenteringyourown

directory.ThisdefaultdirectoryistheDocumentsand

Settingsdirectoryonyourharddrive.

ClicktheOKbuttontocontinue.VS.NETwillcreateanewsubdirectory

namedMyWindowsApplicationinthedirectoryspecifiedinthe

Locationfield.OnceVS.NETcreatesthedirectory,alongwithsome

initialfilesforyourproject,VS.NETwilldisplayablankform,asshownin

Figure6.2.Youcanthinkoftheformasthecanvasonwhichyoucan

placestandardWindowscontrols,suchaslabels,textboxes,and

buttons.You'llbeaddingcontrolstoyourformshortly.







Figure6.2:Ablankform

Inthenextsection,you'lllearnabouttheToolbox,whichyouusetoadd

controlstoyourform.



WorkingwiththeToolbox

YouaddcontrolstoyourformbyselectingthecontrolfromtheToolbox

anddraggingthecontroltoyourform.Youcanalsoclickanddrag,or

double-clickonthecontroltodropanewoneofthattypeontoyourform.

AsyoucanseeinFigure6.2shownearlier,theToolboxistotheleftof

theblankform.

Note Ifyoudon'tseetheToolbox,youcandisplayitbyselecting

View➣Toolbox,orbypressingCtrl+Alt+Xonyourkeyboard.

YoucanseethattheavailableitemsintheToolboxarecategorizedinto

groupswithnamessuchasDataandXMLSchema.TheToolboxwill

showonlycategoriesthatarerelevanttothetypeofapplicationyouare

developing.Thefollowinglistdescribesthecontentsofsomeofthese

categories:

DataTheDatacategorycontainsclassesthatallowyouto

accessandstoreinformationfromadatabase.TheDatacategory

includesthefollowingclasses:SqlConnection,SqlCommand,

DataSet,andDataView,amongothers.

XMLSchemaTheXMLSchemacategorycontainsclassesthat

allowyoutoaccessXMLdata.

DialogEditorTheDialogEditorcategorycontainscontrolsthat

youcanplaceonWindowsdialogboxes.

WebFormsTheWebFormscategorycontainscontrolsthatare

forwebforms.YoucandesignwebformsusingVS.NETand

deploythemtoMicrosoft'sInternetInformationServer(IIS).

ThesewebformsmaythenberunovertheInternet.



ComponentsTheComponentscategorycontainsclassessuch

asFileSystemWatcher,whichallowsyoutomonitorchanges

inacomputer'sfilesystem.OtherclassesincludeEventLog,

DirectoryEntry,DirectorySearcher,MessageQueue,

PerformanceCounter,Process,ServiceController,and

Timer.Theseallowyoutoperformvarioussystemoperations.

WindowsFormsTheWindowsFormscategorycontainscontrols

thatyoucanaddtoaWindowsform.Theseincludelabels,

buttons,andtextboxes,amongothers.You'llusesomeofthese

controlsinthischapter.

HTMLTheHTMLcategorycontainscontrolsthatyoucanaddto

awebform.Theseincludelabels,buttons,tables,andimages,

amongothers.

Inthenextsection,you'lllearnaboutthePropertieswindow.



WorkingwiththePropertiesWindow

ThePropertieswindowcontainsaspectsofacontrolthatyoucanset.For

example,youcansetthebackgroundcolorofyourformusingthe

BackColorproperty.Someotherpropertiesoftheformcontrolinclude

ForeColor(theforegroundcolor)andBackgroundImage(animage

displayedinthebackground).Differenttypesofcontrolshavedifferent

typesofproperties.

AsyoucanseefromFigure6.2shownearlier,thePropertieswindowis

totherightoftheblankform.

Note Ifyoudon'tseethePropertieswindow,youcandisplayitby

selectingView➣PropertiesWindow,orbypressingF4on

yourkeyboard.

Yousetthepropertybyclickingtheareatotherightoftheproperty

name.GoaheadandclicktotherightoftheBackColorpropertytoview

someofthecolorstowhichyoucansetthisproperty.



Inthenextsection,you'lllearnhowtoaddalabelandbuttoncontrolto

yourform.You'llalsosetacoupleofthepropertiesforthosecontrols.



AddingaLabelandaButtonControl

Toaddalabelandabuttoncontroltoyourformselecttheappropriate

controlfromtheToolboxanddragittoyourform.Forexample,toadda

labeltoyourform,youselectthelabelcontrolfromtheToolbox.Once

you'vedraggedalabeltoyourform,youcanresizeitbyusingthemouse

orsettingtheSizepropertyinthePropertieswindow.Youcanalsoclick

onthelabelintheToolboxanddragitonyourform.

Makeyourlabelbigenoughsothatthatitstretchesacrossthelengthof

yourform.Next,addabuttoncontrolbelowyourlabel,asshownin

Figure6.3.





Figure6.3:Theformwithalabelandbuttoncontrol

Next,you'llchangesomeofthepropertiesforyourlabelandbutton.You

dothisusingthePropertieswindow.SettheNamepropertyofyourlabel

tomyLabel.SettheNameandTextpropertiesforyourbuttonto

myButtonandPressMe!,respectively.Also,settheTextpropertyof

yourformtoMyForm.

Note YouusetheNamepropertywhenreferencingaWindows

controlinC#code.



Next,you'lladdalineofcodetothemyButton_Click()method.This

methodisexecutedwhenmyButtonisclickedinyourrunningform.The

statementyou'lladdtomyButton_Click()willsettheTextproperty

ofmyLabeltoastring.ThisstringwillcontainalinefromShakespeare's

play,Macbeth.Toaddthecode,double-clickmyButtonandenterthe

followingcodeinthemyButton_Click()method:

myLabel.Text=

"IsthisadaggerwhichIseebeforeme,\n"+

"Thehandletowardmyhand?Come,letmeclutchthee.\n"+

"Ihavetheenot,andyetIseetheestill.\n"+

"Artthounot,fatalvision,sensible\n"+

"Tofeelingastosight?orartthoubut\n"+

"Adaggerofthemind,afalsecreation,\n"+

"Proceedingfromtheheat-oppressedbrain?";



Note Ifyou'reaShakespearefan,you'llrecognizethislinefromthe

scenebeforeMacbethkillsKingDuncan.

You'venowfinishedyourform.BuildyourprojectbyselectingBuild➣

BuildSolution,orbypressingCtrl+Shift+Bonyourkeyboard.

Torunyourform,selectDebug➣StartwithoutDebugging,orpress

Ctrl+F5onyourkeyboard.

Tip Youcantakeashortcutwhenbuildingandrunningyourform:If

yousimplystartyourformwithoutfirstbuildingit,VS.NETwill

checktoseeifyoumadeanychangestoyourformsinceyou

lastranit.Ifyoudidmakeachange,VS.NETwillfirstrebuild

yourprojectandthenrunit.

Figure6.4showstherunningformafterthePressMe!buttonisclicked.





Figure6.4:Therunningform

Nowthatyou'vecreatedandruntheform,let'stakealookatthecode

generatedbyVS.NETforit.TheC#codeforyourformiscontainedin

thefileForm1.csfile.You'llexaminethiscodeinthenextsection.



ExaminingtheCodebehindtheForm

TheForm1.csfilecontainsthecodeforyourform.Thiscodeisoften

referredtoasthecodebehindyourformbecauseyoucanthinkofitas

beingbehindthevisualdesignforyourform.Youcanviewthecodefor

yourformbyselectingView➣Code,orbypressingtheF7keyonyour

keyboard.Listing6.1showsthecontentsoftheForm1.csfile.

Listing6.1:Form1.cs

usingSystem;

usingSystem.Drawing;

usingSystem.Collections;

usingSystem.ComponentModel;

usingSystem.Windows.Forms;

usingSystem.Data;

namespaceMyWindowsApplication

{

///

///SummarydescriptionforForm1.

///




publicclassForm1:System.Windows.Forms.Form

{

privateSystem.Windows.Forms.LabelmyLabel;

privateSystem.Windows.Forms.ButtonmyButton;

///

///Requireddesignervariable.

///


privateSystem.ComponentModel.Containercomponents=null;

publicForm1()

{

//

//RequiredforWindowsFormDesignersupport

//

InitializeComponent();



//

//TODO:AddanyconstructorcodeafterInitializeCompone

//

}

///

///Cleanupanyresourcesbeingused.

///


protectedoverridevoidDispose(booldisposing)

{

if(disposing)

{

if(components!=null)

{

components.Dispose();

}

}

base.Dispose(disposing);

}

#regionWindowsFormDesignergeneratedcode



///

///RequiredmethodforDesignersupport-donotmodify

///thecontentsofthismethodwiththecodeeditor.

///


privatevoidInitializeComponent()

{

this.myLabel=newSystem.Windows.Forms.Label();

this.myButton=newSystem.Windows.Forms.Button();

this.SuspendLayout();

//

//myLabel

//

this.myLabel.Location=newSystem.Drawing.Point(8,8);

this.myLabel.Name="myLabel";

this.myLabel.Size=newSystem.Drawing.Size(288,184);

this.myLabel.TabIndex=0;

this.myLabel.Text="label1";

//

//myButton

//

this.myButton.Location=newSystem.Drawing.Point(120,20

this.myButton.Name="myButton";

this.myButton.Size=newSystem.Drawing.Size(72,24);

this.myButton.TabIndex=1;

this.myButton.Text="PressMe!";

this.myButton.Click+=newSystem.EventHandler(this.myBut

//

//Form1

//

this.AutoScaleBaseSize=newSystem.Drawing.Size(5,13);

this.ClientSize=newSystem.Drawing.Size(304,237);

this.Controls.AddRange(newSystem.Windows.Forms.Control[]

this.myButton,

this.myLabel});

this.Name="Form1";

this.Text="MyForm";

this.ResumeLayout(false);



}

#endregion

///

///Themainentrypointfortheapplication.

///


[STAThread]

staticvoidMain()

{

Application.Run(newForm1());

}



privatevoidmyButton_Click(objectsender,System.EventArgs

{

myLabel.Text=

"IsthisadaggerwhichIseebeforeme,\n"+

"Thehandletowardmyhand?Come,letmeclutchthee.\n

"Ihavetheenot,andyetIseetheestill.\n"+

"Artthounot,fatalvision,sensible\n"+

"Tofeelingastosight?orartthoubut\n"+

"Adaggerofthemind,afalsecreation,\n"+

"Proceedingfromtheheat-oppressedbrain?";

}

}

}



Asyoucansee,theForm1classisderivedfromthe

System.Windows.Forms.Formclass.TheFormclassrepresentsa

Windowsform.

Note TheSystem.Windows.Formsnamespacecontainsthe

variousclassesforcreatingWindowsapplications.Mostofthe

classesinthisnamespacearederivedfromthe



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 6: Introducing Windows Applications and ADO.NET

Tải bản đầy đủ ngay(0 tr)

×