130 likes | 144 Views
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
E N D
WindowsDialogBoxes, TextBoxes,andList Boxes DialogBoxes •PopupchildwindowscreatedbyWindows •Usedforspecial-purposeinput&output –AprincipalI/OmechanisminWindows •Containseveralchildwindowcontrols •Layout&whatitdoesisarepredefined •In.NETthey’rejustanotherForm –DerivedfromclassForm •Wecandesignourowndialogboxes •Fivepredefined“CommonDialogBoxes”
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
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
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
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
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
ModelessDialogBoxes •Stickaroundafterinvoked •StartwithShow()membermethodofDialogBoxclass –NotShowDialog(),whichstartsitasamodaldialog box –We’llcomebacktotheselater MoreWindowsControls
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
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
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
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
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”,…});
ListBox-SimpleExample •Initiallistboxcontentssetatdesigntime •“AddItem”buttonallowsusertoadditemstothelistboxusingatextbox •“GetCurrentSelection”buttondisplays currently-selecteditemfromthelistboxina labelcontrol ComboBox •VerySimilartoaListBox •HasanassociatedTextBoxcontrol –Textpropertyiswhatistypedbyuser –Textpropertycanbesetincode •DropDownStyleProperty –Simple,DropDown