1 / 13

Dialo g Boxes • Popu p chil d window s create d b y Windows

Windows Dialog Boxes, Tex t Boxes , an d List Boxes. Dialo g Boxes • Popu p chil d window s create d b y Windows • Use d fo r specia l - purpos e inpu t & output – A principa l I/ O mechanis m i n Windows • Contai n severa l chil d windo w controls

faulks
Download Presentation

Dialo g Boxes • Popu p chil d window s create d b y Windows

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. WindowsDialogBoxes, TextBoxes,andList Boxes DialogBoxes •PopupchildwindowscreatedbyWindows •Usedforspecial-purposeinput&output –AprincipalI/OmechanisminWindows •Containseveralchildwindowcontrols •Layout&whatitdoesisarepredefined •In.NETthey’rejustanotherForm –DerivedfromclassForm •Wecandesignourowndialogboxes •Fivepredefined“CommonDialogBoxes”

  2. TypesofDialogBoxes •Modal •Modeless •SystemModal CommonDialogBoxes •PredefinedModalDialogBoxesthatenableusertoperformcommonI/Ooperationsinastandardway •Fiveofthem--alldatebacktoWindows3.1 –FileDialog •Open/Savefilesinaneasyandstandardway –ColorDialog •Choosecolorsinaneasyandstandardway –FontDialog •Selectfontsinaneasyandstandardway –PageSetupDialog –PrintDialog •Bothrelatedtoprinting •Containedinclassesderivedfrom System.Windows.Forms.CommonDialog •Userinteractionswithcommondialogboxsetpropertiesthatcanberead&usedafterwards

  3. UsingCommonDialogBoxes 1.Instantiateacommondialogobject,e.g.ColorDialog: ColorDialogcolordlg=newColorDialog(); 2.Setitsproperties(optional) colordlg.Color=this.BackColor; 3.CallitsShowDialog()methodtoinvokethedialogbox •SinceModal,executionhaltsuntiluserdismissesthedialogbox colordlg.ShowDialog(); 4.Afteritreturns,useitspropertieschangedbyuseractions this.BackColor=colordlg.Color; –Almostalwayscontain“OK”&“Cancel”buttons •“Abort”,“Ignore”,“No”,“Retry’,‘Yes”buttonsarealsodefined •ButtonpressedbyuseriscontainedinShowDialog()returnvalue –E.g.,DialogResult.OK,DialogResult.Cancel,etc. if(colordlg.ShowDialog()==DialogResult.OK) this.BackColor=colordlg.Color; –Exampleprogram:Common-Color-Dialog •Notebuttoninheritsthenewcolor CommonFontDialogBox •Allowstheusertochangefonts •ClassFontDialog –Properties: •Fontfont •ColorColor •boolShowColor •boolShowEffects •boolShowApply •boolShowHelp –InstantiateandstartwithShowDialog()memberfunctionjustasfortheCommonColordialogBox •Exampleprogram:Common-Color-Font-Dialog

  4. UsingVisualStudioDesignertoCreate CommonDialogBoxes •Justdragthemfromthetoolboxontotheform •Theirpropertiescanbeaccessedeasilyintheir PropertiesWindows •Stillhavetowritecodetoinvokethem –ShowDialog() •Andcodetousetheirchangedproperties –Common-Color-Dialog-Designerexample Programmer-DefinedDialogBoxes •DefineourowndialogboxescontainingwhatevercontrolsarerequiredforcustomI/O •JustdefineandinstantiateasecondclassderivedfromclassFormintheapplication –Encapsulateseverythingaboutthedialogbox –Setdesiredproperties –Adddesiredcontrolsandeventhandlers –Startitwiththeobject’sShowDialog()method –Mainform’scodestopsexecutinguntiluserdismissesthedialogbox •DialogResultpropertyreturnedbyShowDialog()willidentifywhichbuttonindialogboxwaspressedtoterminateit

  5. Dialog-ManualExampleProgram •MainformcreatedwithVSDesignerasusual –Containsa“StartDialogBox”buttonAndaLabelcontrol •Whenuserclicksthebutton,amodaldialogboxwith“OK” and“Cancel”buttonsappears •Thenameofthebuttonpressedbytheusertodismissthedialogboxwillbedisplayedinthemainform’slabelcontrol –Thedialogbox’sbuttons,properties,andbuttonclick handlermethodsarealldefinedinasecondFormclass •HandlersshouldsetDialogBox’sDialogResultproperty –Thesecondformclasswascodedmanuallyinsamefile •EasiertouseVisualStudiotoaddtheseconddialogboxclass,setitsproperties,andadditsbuttonclickhandlers Dialog-DesignerExampleProgram •SamefunctionalityasDialog-Manualapplication •Adddialogbox –WithprojectnameselectedinSolutionExplorer: •Selectfrommainmenu:Project|AddNewItem|WindowsForm •OrrightclickonprojectnameandselectAdd|WindowsForm –Ineithercasethe“AddNewItem”dialogboxcomesup •ChangethedefaultnametoSimpleDialogBox –VSDesignerwillcreateanewfilecontainingthenewclass –Asusual,addthe“OK”&“Cancel”buttonstothenewformbydraggingthemfromthetoolbox –Andaddtheirclickeventhandlersbydoubleclickingonthemorusingthepropertieswindow(lightningbolt) •Add“StartDialogBox”buttononmainform •Anditsclickeventhandlerasusual –Inthishandleraddcodetoinstantiatethedialogbox,setitsproperties,andstartit

  6. GettingDatafromaDialogBox •Dialogboxesusuallyallowusertoprovidedatafortheapplication •Howtogetdatafromthedialogboxtotheparentform: –Couldusepublicfields(variables) •Sootherclasses(theparentform)canaccessthem –Bettertousepublicproperties •Forprotectedaccesstoprivatefields –Mustbedefinedinthedialogboxclass –Propertieswiththeirget/setaccessorscanbecodedmanually –SeeDlgBoxPropertiesTestExample •DisplayswhichofthreebuttonsinaDialogBoxwaspressed •Noteuseofthis.Close()inExitbuttonhandlertodismisstheDialogBox Radio-Check-DialogExample •Radio-Checkapplicationmodifiedusingadialogbox –Twoclasses: •ColorFillDialogBoxclassencapsulatesadialogboxthatallowsthe usertochooseacolorandfilloption –Colorsareshowninradiobuttonsina“Color”groupbox »Createandaddtheradiobuttonsinaloop »Selectedcolor(ColorRect)isapublicPropertyaddedtotheclass get/setaccessorsindexthruallcontrolsintheColorgroupbox »NoteuseofColor.FromName(…)thatcreatesaColorfromastring –“FillRectangle”isacheckbox »Checkboxstate(Fill)isanotherpublicPropertyaddedtotheclass get/setaccessorsreturn/settheCheckedstateofthecheckbox •MainForm1classhasabuttontostartthedialogbox –DialogBox’sColorRectandFillPropertiesareusedtochangeclass-levelvariablescolorRectandbFillRectafterdialogboxisdismissed –Painteventisforced »PainthandlerdrawsorfillsarectangleaccordingtothevaluesofcolorRectandBFillRect

  7. ModelessDialogBoxes •Stickaroundafterinvoked •StartwithShow()membermethodofDialogBoxclass –NotShowDialog(),whichstartsitasamodaldialog box –We’llcomebacktotheselater MoreWindowsControls

  8. TextInputControls •TextBox –FormerlycalledanEditControl –Allowsusertotypeintext •Canbesinglelineormultiline •ListBox –Presentsascrollablelistofselectionsforuserto choose •ComboBox –CombinesthefeaturesofaTextBoxandaListBox TextBoxes •SimplestisderivedfromTextBoxclass –RichTextBoxclassprovidesadditionalfunctionality –BotharederivedfromTextBoxBaseclass •SomeProperties: –stringText –intMaxLength//max#ofcharacters –intTextLength//(getonly) –boolMultiline –string[]Lines//formultilinetextboxes –intLines.Length//#oflines •Mostusefulevent: –TextChanged--actuallydefinedinControlparentclass –Method:OnTextChanged() –Delegate:EventHandler –Argument:EventArgs

  9. TextBox-SimpleExampleProgram •CreatesaTextBoxandaLabelcontrol •AnytimeuserchangestextintheTextBox,itisreproducedintheLabelcontrol –ProgramhandlestheTextBox’sTextChanged event •CreatedwithVSDesigner –JustdragtheTextBoxandLabelfromthetoolbox,changetheirproperties,andaddtheTextChangedeventhandler MultiLineTextBoxes •JustsetMultilinepropertytotrue •Anotherproperty: –Lines •Anarrayofstringsthatcontainsthetextenteredbyuser •Sinceit’sanarray,LinesalsohasaLengthproperty •Canaddscrollbars –ScrollBarsproperty: •None,Horizontal,Vertical,Both •Forhorizontaltowork,WordWrappropertymustbesettofalse •GiveNotepad-likefunctionality •Example:TextBox-Multiline

  10. Non-textualDatainaTextBox •UseParse()methodtoconvertTextpropertyofacontroltoitsnumericformbeforeusingitinacomputation •EachdatatypehasitsownParse()method,e.g.: –int.Parse();float.Parse();decimal.Parse(); •Example–twotextboxescontainstringsthatrepresentnumbers: –numTxtBoxandpriceTxtBox –Todocomputationsneedtoconverttonumericvalues: intnum=int.Parse(numTxtBox.Text);//getnumberofitems decimalprice=decimal.Parse(priceTxtBox.Text);//getpriceperitem floattotPrice=price*num;//computetotalprice FormattingDataforDisplay •DisplaynumericdataintheTextpropertyofa Label,Textbox,orListbox •UseToString()and“formatspecifiercodes” –Canformatanumericvaluetoastringcontainingsuchfeaturesas:$,comma,decimalpoint,% –Alsocanspecify#ofdigitstorightofdecimalpoint •xxx.ToString(“formatcode”) •Someformatcodes(example:1123.42817): –“C”currency$1,123.43 –“F0”fixedpoint1123 –“F3fixedpoint1123.428 –“N”number1,123.43 –“N3”number1123.428

  11. Compute-InterestExample •TextBoxesfor: –Principal,InterestRate,NumberofYears •Labelsforeach •LabelforcomputedTotalInterest •ComputesTotalInterest: –Interest=Principal*Rate*Years –NoteParsingtogetvaluesfromTextBoxes –Andformattingtodisplayresult –AlsonoteuseofMorFsuffixonnumericconstants •M:decimal •F:float •C#defaultstodouble •Butwhatifuserentersthewrongtypeofdata? –Useatry/catchblock –SeeComputeInterestTryCatchexample ListBoxesandComboBoxes •ListBox –Containslistsofitemsthatcanbeselected –Entirelistisshown –Userselectsitems –Selecteditemishighlighted –EncapsulatedinclassListBox •ComboBox –Textboxcombinedwithalistbox –Listboxcanbedisplayedatalltimesorpulleddown –Userselectsitemfromlist&itemiscopiedtotextbox –Onetypeallowsusertotypeintotextbox –EncapsulatedinclassComboBox •Forboth,scrollbarsareaddedautomaticallyasneeded

  12. ListBox“Items”Property •ThelistofItemsinalistboxisacollection(likeArrayList) –Thesecollectionshavemethodsthatallowprogrammerto: •Additems,insertitems,removeitems,refertoindividualitems,countitems,getselecteditem,&clearthecollection –listBox1.Items.Add(ItemValue); –listBox1.Items.Insert(IndexPosition,ItemValue); –listBox1.Items.Remove(ItemValue); –listBox1.Items.RemoveAt(IndexPosition); –Referringtoagivenitem: •listBox1.Items[IndexPosition]; –Numberofitemsinlist •listBox1.Items.Count –SelectedIndexProperty–storesindexofitemselected •intx=listBox1.SelectedIndex;//retrieveindexofselecteditem •listBox1.SelectedIndex=3;//selectitem3(willappearselected) –listBox1.Items.Clear();//removeallitemsfromlist UsingDesignertoFillaListBoxat DesignTime •SelecttheListBoxcontrolontheform •ScrollPropertieswindowto“Items”property •Clickon“…”toopen“StringCollectionEditor” –Typeintheitemsinthelist,endingeachwithEnterkey •NoteinDesignerGeneratedCode: –listBox1.Items.AddRange(newobject[]{“str1”,“str2”,…});

  13. ListBox-SimpleExample •Initiallistboxcontentssetatdesigntime •“AddItem”buttonallowsusertoadditemstothelistboxusingatextbox •“GetCurrentSelection”buttondisplays currently-selecteditemfromthelistboxina labelcontrol ComboBox •VerySimilartoaListBox •HasanassociatedTextBoxcontrol –Textpropertyiswhatistypedbyuser –Textpropertycanbesetincode •DropDownStyleProperty –Simple,DropDown

More Related