Tải bản đầy đủ - 0 (trang)
Hour 7. Working with the Traditional Controls

Hour 7. Working with the Traditional Controls

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

Hour7.WorkingwiththeTraditionalControls

Theprevioustwohoursdescribedinconsiderabledetailhowto

work with forms. Forms are the foundation of a user interface

but are rather useless by themselves. To create a usable

interface, you'll need to use controls. Controls are the various

widgets and doodads on a form with which a user interacts.

Dozens of different types of controls exist, from the simple

Label control used to display static text to the rather

complicatedTreeViewcontrolusedtopresenttreesofdatalike

that found in Explorer. In this hour, I'll introduce you to the

most common (and most simple) controls, which I call

traditional controls. In the next hour, you'll learn about the

moreadvancedcontrolsthatyoucanusetocreateprofessionallookingapplications.

Thehighlightsofthishourincludethefollowing:

DisplayingstatictextwiththeLabelcontrol

Allowinguserstoentertextusingatextbox

Creatingpasswordfields

Workingwithbuttons

Usingpanels,groupboxes,checkboxes,andoptionbuttons

Displayinglistswithlistboxesandcomboboxes







Top











DisplayingStaticTextwiththeLabelControl

Label controls are used to display static text to the user. By

static,Imeanthattheusercan'tchangethetextdirectly(but

you can change the text with code). Label controls are one of

themostcommoncontrolsused;fortunately,they'realsooneof

the easiest. Labels are most often used to provide descriptive

textforothercontrols,suchastextboxes.Labelsarealsogreat

for providing status-type information to a user, as well as for

providinggeneralinstructionsonaform.

Begin by creating a new Windows Application named

TraditionalControls.Changethenameofthedefaultformto

fclsControls, and change its Text property to Traditional

ControlsExample. Next, change the Main entry point to use

flcsControls.

Add a new Label control to the form by double-clicking the

Label item in the toolbox. The primary property of the Label

controlistheTextproperty,whichdeterminesthetextdisplayed

to the user. When a Label control is first added to a form, the

Text property is set to the name of control—this isn't very

useful.SetthepropertiesofthenewLabelcontrolasfollows:

Property



Value



Name

Location

Size

Text



lblMyLabel

5,6

100,25

Labelsareforstatictext!



Notice how the label's text appears on two lines (see Figure

7.1).Thisoccursbecausethetextisforcedtofitwithinthesize



of a new Label control. In most cases, it's best to place label

text on a single line. To do this, you could increase the width

eitherbyusingthePropertieswindoworbydraggingtheedge

ofthecontrol,butthereisaneasierway.Double-clicktheLabel

control's AutoSize property now and notice how the label

resizes itself automatically to fit the text on a single line.

Double-clickingapropertythatacceptsasetnumberofvalues

cyclesthepropertytothenextvalue.TheAutoSizepropertyof

new Label controls is false by default, so double-clicking this

propertychangedittotrue.

Figure7.1.Labelsdisplaystatictext.









Top











AllowingUserstoEnterTextUsingaTextBox

ALabel control is usually the best control for displaying text a

user can't change. However, when you need to let users enter

oredittext,thetextboxisthetoolforthejob.Ifyou'veever

typed information on a form, you've almost certainly used a

text box. Add a new text box to your form now by doubleclicking the TextBox item in the toolbox. Set the text box's

propertiesasfollows:

Property



Value



Name

Location

Size



txtMyTextBox

128,4

136,20



Whenyoufirstcreateanewtextbox,itsTextpropertyissetto

its default name (see Figure 7.2). Unfortunately, the Text

property isn't automatically changed when you change the

name of the text box (which you should always do), so I

recommend that you clear out the Text property of new text

boxes.DeletethetextintheTextpropertynowandnoticethat

thetextboxappearsemptyontheform.

Figure7.2.AnewtextboxhasitsTextpropertysettoits

defaultname.



Althoughyou'llprobablywanttocleartheTextpropertyofmost

of your text boxes at design time, understanding certain

aspectsofthetextboxiseasierwhenatextboxcontainstext.

Set the text box's Text property to This is sample text.

Remember to press Enter or Tab to commit your property

change.



SpecifyingTextAlignment

Both the TextBox and the Label controls have a TextAlign

property (as do many other controls). The TextAlign property

determines the alignment of the text within the control—very

muchlikethejustificationsettinginawordprocessor.Youcan

selectfromLeft,Center,orRight.



Label controls allow you to set the vertical alignment

and the horizontal alignment using the TextAlign

property.ThisworksbestwhenAutoSizeissettofalse.



ChangetheTextAlignpropertyofthetextboxtoRight,andsee

how the text becomes right-aligned within the text box. Next,

changeTextAligntoCentertoseewhatcenteralignmentlooks

like. As you can see, this property is pretty straightforward.

ChangetheTextAlignpropertybacktoLeftbeforecontinuing.



CreatingaMultilineTextBox

In the previous hour, I talked about the sizing handles of a

selected control. I mentioned how handles that can be sized

appear filled with white, and handles that are locked appear

with a gray center. Notice how only the left and right edges of

thetextboxhavewhitesizinghandles.Thismeansthatyoucan

adjustonlytheleftandrightedgesofthecontrol(youcanalter

onlythewidth,nottheheight).Thisisbecausethetextboxis

defined as a single-line text box, meaning it will display only

onelineoftext.Whatwouldbethepointofareallytalltextbox

thatshowedonlyasingleline?

To allow a text box to display multiple lines of text, set its

Multilinepropertytotrue.SettheMultilinepropertyofyourtext

boxtotruenow,andnoticethatallthesizinghandlesbecome

white.

Change the Text property of the text box to This is sample

text. A multiline text box will wrap its contents as

necessary.PressEnterorTabtocommitthepropertychange.

Noticehowthetextboxdisplaysonlypartofwhatyouentered

becausethecontrolsimplyisn'tbigenoughtoshowallthetext

(see Figure 7.3). Change the Size property to 136,60, and

you'll then see the entire content of the text box (see Figure

7.4).

Figure7.3.Atextboxmaycontainmoretextthanitcan



display.



Figure7.4.Amultilinetextboxcanbesizedaslargeas

necessary.



At times, you won't want a user to be able to interact with a

control. For instance, you may implement a security model in

your application, and if the user doesn't have the necessary

privileges,youmaynotwanttheusertobeabletoalterdata.

The Enabled property, which almost every control has,

determines whether the user can interact with the control.

ChangetheEnabledpropertyofthetextboxtofalse,andpress

F5toruntheproject.Althoughnonoticeablechangeoccursin

thecontrolinDesignview,thereisabigchangetothecontrol

atruntime:thetextappearsingrayratherthanblack,andthe

textboxwon'tacceptthefocusorallowyoutochangethetext

(seeFigure7.5).

Figure7.5.Youcan'tinteractwithatextboxwhose

Enabledpropertyissettofalse.



Stop the project now by choosing Stop Debugging from the

Debug menu, and then change the control's Enabled property

backtotrue.



AddingScrollbars

Even though you can size a multiline text box, there may be

timeswhenthecontentsofthecontrolaremorethanwhatcan

be displayed. If you believe that this is a possibility for a text

box you're adding to a form, give the text box scrollbars by

changing the ScrollBars property from None to Vertical,

Horizontal,orBoth.



For a text box to display scrollbars, its Multiline

propertymustbesettotrue.



ChangetheScrollBarspropertyofyourtextboxtoVerticaland

noticehowscrollbarsappearinthetextbox(seeFigure7.6).

Figure7.6.Ifatextboxmaycontainlotsoftext,giveita

scrollbar.



LimitingtheNumberofCharactersaUserCanEnter

Youcan limit the number of characters a user can type into a

textboxusingtheMaxLength property. All new text boxes are

given the default value of 32767 for MaxLength, but you can

changethisasneeded(upordown).Addanewtextboxtothe

formandsetitspropertiesasfollows:

Property



Value



Name



txtRestrict



Location

MaxLength

Size

Text



128,80

10

136,20

(makeblank)



RuntheprojectbypressingF5andthenenterthefollowingtext

intothetextbox:Soyourunandyourun.Besuretotryto

enter more than 10 characters of text—you can't (if you can,

you're probably entering the text into the text box with

scrollbars, rather than into the new text box). All that you're

allowed to enter is So you run (10 characters). The text box

allows only 10 characters, whether that's via entry using the

keyboardoraPasteoperation.TheMaxLengthpropertyismost

often used when the text box's content is to be written to a

database, in which field sizes are usually restricted (using a

databaseisdiscussedinHour21,"WorkingwithaDatabase").

Stop the project by choosing Stop Debugging from the Debug

menuandthenclickSaveAllonthetoolbar.



CreatingPasswordFields

You'veprobablyusedapasswordfield:atextboxthatdisplays

an asterisk for each character entered. Any text box can be

made a password field by assigning a character to its

PasswordChar field. Select the PasswordChar property of the

secondtextboxnow(txtRestrict)andenteranasterisk(*)for

the property value. Run the project once more and enter text

into the text box. Now an asterisk is displayed for each

characteryouenter(seeFigure7.7).Althoughtheuserdoesn't

see the actual text contained in the text box, referencing the

Textpropertyincodealwaysreturnsthetruetext.

Figure7.7.Apasswordfielddisplaysitspassword



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

Hour 7. Working with the Traditional Controls

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

×