• Tidak ada hasil yang ditemukan

Directory listing of http: uap.unnes.ac.id ebook biblebook Visual Basic 6 com & Library Books

N/A
N/A
Protected

Academic year: 2017

Membagikan "Directory listing of http: uap.unnes.ac.id ebook biblebook Visual Basic 6 com & Library Books"

Copied!
22
0
0

Teks penuh

(1)

M ore About

Bound Controls

I

n the previo us c hapter, I sho wed yo u ho w to build a pro -gram witho ut any c o de using o nly bo und c o ntro ls and the ADO Data Control. In this c hapter, I will c o ntinue disc ussing bo und c o ntro ls by talking abo ut so me o ther pro perties and events that yo u c an use to help ensure that o nly valid data is sto red in yo ur database. Then I’m go ing to disc uss a few o ther useful c o ntro ls that have spec ial features to help ensure that yo ur data is c o rrec t befo re it gets into the database.

Bound Controls Revisited

Bo und c o ntro ls are no t as simple as I led yo u to believe in Chapter 7. There are several o ther pro perties, metho ds, and events that allo w yo u to fine-tune ho w the user interac ts with the c o ntro l.

Key properties

All bo und c o ntro ls c o ntain the pro perties listed in Table 8-1, whic h affec t the way the c o ntro l wo rks with the user and with the database.

Key methods

(2)

Table 8-1

Key Properties of Bound Controls

Property Description

CausesValidation A Booleanvalue, w here TRUEm eans that the Validation event for the control previously focused w ill be fired before the focus is shifted to this control.

DataChanged A Booleanvalue, w here TRUEm eans that either the user has changed the value of the control or the program has changed the value of the control.

DataField A Stringvalue containing the field nam e to w hich the control is bound.

DataFormat An object reference to an StdDataFormatobject w hich contains inform ation about how to form at the value displayed by the control.

DataMember A Stringvalue that identifies w hich set of data should be used w hen a DataSourcehas m ore than one set of data.

DataSource An object reference to an object that can act as a data source. Com m on data sources include the ADO Data Control, a Recordsetobject or a Class m odule w here the DataSourceBehaviorproperty is set to

vbDataSource(1).

Object

.SetFocus ( )

The SetFocusmetho d is used to transfer the fo c us to the c o ntro l spec ified b y

o bje ct. If the c o ntro l spec ified b y o bje ctisn’t visib le o r c an’t ac c ept the fo c us, a runtime erro r will o c c ur.

Key events

Mo st c o ntro ls that c an be bo und have a set o f events that will be fired as the user interac ts with the c o ntro l. These events c an be used to verify that the info rmatio n a user enters into the c o ntro l is c o rrec t.

Event Change ( )

(3)

Event GotFocus ( )

The GotFocusevent fired befo re a c o ntro l rec eives the fo c us.

Event KeyDown (KeyCode As Integer, Shift As Integer)

The KeyDownevent is fired whenever the user presses a key while the c o ntro l has the fo c us, where KeyCodeis an Integervalue c o ntaining the key c o de o f the key that was pressed. This value is no t the ASCII c harac ter value asso c iated with the key.

Shiftis an Integervalue that indic ates the status o f the Shift, Alt, and Ctrl keys.

Event KeyPress (KeyAscii As Integer)

The KeyPressevent is fired whenever a key is pressed and released, where KeyAscii c o ntains the ASCII c o de o f the key that was pressed. Changing this value to zero in the event c anc els the keystro ke.

Event KeyUp (KeyCode As Integer, Shift As Integer)

The KeyUpevent is fired whenever the user releases a key while the c o ntro l has the fo c us, where KeyCodeis an Integervalue c o ntaining the key c o de o f the key that was released. This value is no t the ASCII c harac ter value asso c iated with the key.

Shiftis an Integervalue that indic ates the status o f the Shift, Alt, and Ctrl keys.

Event LostFocus ( )

The LostFocusevent is fired just befo re the fo c us is transferred to ano ther c o ntro l.

Event Validate (Cancel As Boolean)

The Validateevent is used to verify that the c o ntents o f a c o ntro l are valid befo re the fo c us is shifted to ano ther c o ntro l. The Validateevent will o nly be triggered if the destinatio n c o ntro l has the CausesValidationpro perty set to TRUE. This is the c ase where Cancelis a Booleanvalue, and TRUEmeans that the fo c us sho uld no t be shifted to the next c o ntro l. By default, Cancelis set to FALSE.

Data validation

There are basic ally fo ur ways to verify that the user has entered the c o rrec t data into a c o ntro l like a TextBox:

✦Changeevent

✦KeyPress, KeyUp, and KeyDownevents

✦GotFocusand LostFocusevents

(4)

Eac h appro ac h is disc ussed b elo w, alo ng with any o f its advantages and disad-vantages.

Using the Change event

The Changeevent is triggered eac h time the value o f the c o ntro l is c hanged. While at first this may be the ideal event with whic h to verify c hanges, it turns o ut it is the least prac tic al appro ac h.

Co nsider a TextBoxc o ntro l. Eac h time the user types a c harac ter into the text win-do w, the c hange event is fired. Also , anytime yo u c hange the Textpro perty in yo ur pro gram, yo u trigger the Changeevent. This c an make things really c o mplic ated if yo u c ho o se to c hange the value o f the c o ntro l while in the Changeevent.

Using the KeyPress, KeyUp, and KeyDown events

The KeyPress, KeyUp,and KeyDownevents are fired whenever a user presses a key o n the keybo ard. Like the Changeevent, these events are so mewhat limited in their usefulness fo r validating data. Ho wever, yo u c an trap the keystro kes as they are entered and translate them into so mething o r perfo rm a spec ial task.

Fo r instanc e, yo u c an inc lude so me c o de in the KeyPressevent to translate any lo werc ase c harac ters into their upperc ase equivalents auto matic ally. Yo u c an also define c ertain keystro kes, suc h as the Esckey, to perfo rm spec ial func tio ns, like resto ring the o riginal value fo r the field fro m the database ( see Listing 8-1) .

Listing 8-1:

The Text1_KeyPress event in Customer

Information Editor

Private Sub Text1_KeyPress(KeyAscii As Integer) If Chr(KeyAscii) >= “a” And Chr(KeyAscii) <= “z” Then

KeyAscii = KeyAscii - 32

ElseIf (KeyAscii = 27) And Text1.DataChanged Then

Text1.Text = Adodc1.Recordset.Fields(“Name”).OriginalValue KeyAscii = 0

End If End Sub

Looking to the future: One of the properties of the ADO Data Control is a refer-ence to the underlying Recordsetobject containing the data retrieved from the database. I’ll cover the Recordsetobject in detail starting w ith Chapter 11.

(5)

Using the LostFocus event

In Listing 8-2, I use the LostFocusevent to determine if the user has left the field blank. If so , I turn the bac kgro und red to indic ate that this field has an erro r. After the user has entered so me data and leaves the c o ntro l again, I return the no rmal bac kgro und c o lo r fo r the text bo x. Of c o urse, sinc e I o nly c hange the c o lo r in the LostFocusevent, the erro r will still be flagged after the user returns the fo c us to the c o ntro l. Yo u c an leave it this way, o r yo u c an add so me c o de in the GotFocus event to reset the erro r flag.

Listing 8-2:

The Text1_LostFocus event in Customer

Information Editor

M ake an error stand out:No m atter how you determ ine that the contents of a field are invalid, you should include som e code to tell the user in no uncertain term s that the value is incorrect. You could include a line such as Text1.BackColor = &HFF&to turn the background of a text box red in the LostFocusevent and use a line of code like Text1.BackColor = &H80000005 to restore the proper background color. You could also use other colors to display different status conditions, such as yellow (&HFFFF&) to w hen a field should not be left blank.

Resetting focus in the LostFocus event: When your program handles the LostFocusevent, the focus has already begun the process of shifting to the next control. If you try to use the SetFocusm ethod inside the LostFocusevent to bring the focus back to the current control, the next control w ill briefly receive the focus, and its GotFocusand LostFocusevents w ill be fired.

(6)

Using the Validate event

Pro bably the best way to verify that the data entered by a user is ac c eptable is to put the test in the Validateevent. When the user attempts to switc h the fo c us to ano ther c o ntro l, the Validateevent is fired. If the value in the c o ntro l isn’t ac c ept-able, all yo u need to do is set the Cancelparameter to TRUEand the fo c us will remain with the c urrent c o ntro l witho ut triggering the GotFocus/LostFocusevents o f the o ther c o ntro l.

Unlike the o ther appro ac hes to validating data whic h o perate o n a single c o ntro l at a time, using the Validatemetho d requires that yo u c o o rdinate all o f the c o ntro ls o n a single fo rm. In general, all o f the c o ntro ls o n the fo rm that are c apable o f rec eiving the fo c us need the CausesValidationpro perty set to TRUE. The o nly c o ntro ls that sho uldn’t have CausesValidationset to TRUEare tho se that wo uld allo w the user to abo rt any c hanges.

Fo r example, c o nsider a fo rm like the o ne in Figure 8-1. There are three text bo xes and two c o mmand butto ns that c an rec eive the fo c us. Eac h o f these c o ntro ls has the CausesValidatepro perty set to TRUE, exc ept fo r the Canc el butto n. This means that the Validateevent will be triggered when the user tries to shift the fo c us o n any o f the text bo xes o r the Update butto n.

Figure 8-1: Validating data on a form

A typic al Validateevent is sho wn in Listing 8-3. In this ro utine, I merely verify that the text bo x is no t empty. If it is, then I’ll turn the bac kgro und to red and display an erro r message in the status bar. Then I’ll set the Cancelparameter to TRUEto pre-vent the user fro m mo ving the fo c us to ano ther c o ntro l.

Listing 8-3:

The Text1_Validate Event in Validate Event Demo

Private Sub Text1_Validate(Cancel As Boolean) If Len(Text1.Text) = 0 Then

Text1.BackColor = &HFF&

(7)

Cancel = True End If

End Sub

Sinc e the Canc el butto n has the CausesValidationpro perty set to FALSE, even if there is an erro r in o ne o f the text bo xes, the fo c us c an be transferred to the Canc el butto n. Thus, yo u c an use this butto n to undo any c hanges o r reset the info rmatio n displayed in the o ther c o ntro ls to their default values.

Explain what caused the error:In addition to m aking your error stand out, you m ay w ant to explain the error in m ore detail. While you can alw ays display the error m essage using a m essage box, consider adding a StatusBar control at the bottom of the form and displaying the error m essage inside one of the panels. This allow s you to display the error m essage w ithout unnecessarily disrupting the user’s w ork.

Formatting data

Ano ther ability o f many bo und c o ntro ls is the ability to fo rmat auto matic ally the data they display. Yo u c an spec ify the fo rmat info rmatio n in the DataFormatpro p-erty. Yo u c an spec ify the fo rmat info rmatio n at design time ( see Figure 8-2) o r at runtime using the StdDataFormato bjec t ( see Table 8-2) .

Figure 8-2: Specifying a form at for your data

(8)

Typic ally, yo u’re go ing to set the fo rmat fo r a field at design time. Simply c ho o se the appro priate Fo rmat Typefo r the value yo u want to fo rmat and a set o f o ptio ns will appear under the Fo rmatheading c o rrespo nding to the Fo rmat Typeyo u selec ted.

Table 8-2

Key Properties of the StdDataFormat Object

Property Description

FalseValue A Variantcontaining the value to be displayed w hen a Booleanfield is FALSE.

FirstDayOfWeek An enum erated value that contains the value of the first day of a w eek. This inform ation is used to com pute values such as the w eek of the year. Legal values are fmtDayUseSystem(0), fmtSunday(1),

fmtMonday(2), . . . and fmtSaturday(7).

FirstWeekOfYear An enum erated value that contains inform ation about how to determ ine the first w eek of the year. Legal values are fmtWeekUseSystem(0),

fmtFirstJan1(1), fmtFirstFourDays(2), and

fmtFirstFullWeek(3).

Format A Stringvalue containing a standard form at string.

NullValue A Variantcontaining the value to be displayed for a

Nullvalue.

TrueValue A Variantcontaining the value to be displayed w hen a Booleanfield is TRUE.

Type An enum erated value that describes the type of inform ation being displayed from the database. Legal values are: fmtGeneral(0), fmtCustom(1),

fmtPicture(2), fmtObject(3), fmtCheckbox

(4), fmtBoolean(5), and fmtBytes(6).

Numbers and names: Visual Basic often allow s you to specify the value of a prop-erty by nam e rather than by num ber. This is know n as an enumerated value. You should use enum erated values w henever possible to m ore clearly docum ent the value you are using.

(9)

Using the Picture and Image Controls

Displaying graphic images in yo ur database is very easy when yo u use a bo und Pictureo r Imagec o ntro l. Unlike the o ther bo und c o ntro ls, these c o ntro ls are stric tly o ne way. They c an display data fro m yo ur database, but c hanging the image displayed in the c o ntro l will no t update the image in yo ur database when the rest o f the ro w is updated.

The key to using these c o ntro ls is to bind them to a c o lumn in yo ur database c o n-taining the raw image. The image c an be in any fo rmat that is ac c eptable to the LoadPicturefunc tio n, inc luding .BMP, .JPG, and .GIF. The type o f image will auto -matic ally be detec ted and pic ture will auto -matic ally be lo aded into the c o ntro l.

Yo u c an’t assign an image sto red in yo ur database direc tly to the Picturepro perty o f the Pictureo r Imagec o ntro ls. Yo u must either save the c o lumn’s value to a file and then use the LoadImagefunc tio n o r bind the c o ntro l direc tly to the database.

Aren’t they the same? The Imageand Picturecontrols can both be used to dis-play im ages. All of the data binding properties are the sam e. How ever, the Picturecontrol has the ability to act as a container for other controls, and it also includes a rich set of draw ing m ethods that are not found on the Imagecontrol.

Using the M asked Edit Control

The Masked Editc o ntro l is an alternative to o f the text bo x c o ntro l. It inc ludes the ability to c o mpare inc o ming keystro kes against an input mask that determines whether the keystro ke is valid o r no t. Using a simple mask c an ensure that numeric fields will c o ntain o nly numeric values, and with mo re c o mplex masks, yo u c an enter and display mo re c o mplex values, suc h as telepho ne numbers and so c ial sec urity numbers (see Figure 8-3).

Figure 8-3: Entering a num eric value for the ZIP code.

Invalid social security numbers:The m iddle tw o digits of a social security num -ber (AAA-BB-CCCC) are never 00. The program m ers at the Social Security Adm inistration use social security num bers w ith 00 in the m iddle to test their applications.

(10)

Key properties

The Masked Editc o ntro l c o ntains all o f the standard pro perties fo und in an aver-age Ac tiveX c o ntro l, suc h as Top, Left, Width, Height, Enabled, ToolTipText, etc . Ho wever there are a few key pro perties that affec t the way the c o ntro l wo rks ( see Table 8-3) .

Table 8-3

Key Properties of the M asked Edit Control

Property Description

AllowPrompt A Booleanvalue, w here TRUEm eans that PromptCharis a valid input character.

AutoTab A Booleanvalue, w here TRUEm eans that the control w ill autom atically tab to the next field w hen this field is full.

ClipMode An enum erated data type that determ ines if the literal characters displayed in the input m ask w ill be included in a copy or cut operation. A value of mskIncludeLiterals(0) m eans that the characters w ill be included, w hile a value of mskExcludeLiterals

(1) m eans that the characters w ill not be included.

ClipText A Stringcontaining the contents of the control, w ithout any literal characters.

Format A Stringcontaining up to four form at strings separated by sem icolons that w ill be used to display the inform ation in the control.

FormattedText A Stringcontaining the text that w ill be displayed in the control w hen another control has the focus.

HideSelection A Booleanvalue, w here TRUEm eans that selected text w ill not be highlighted w hen the control loses focus.

Mask A Stringvalue containing the input m ask. Table 8-4 contains a list of legal m ask characters. Any other character in the input m ask is considered a literal character.

MaxLength An Integercontaining the m axim um length of the input data.

(11)

Property Description

PromptInclude A Booleanvalue, w here TRUEm eans that PromptCharis included in the Textproperty. For bound controls TRUEm eans that the value in the Textproperty w ill be saved in the database and FALSEm eans that the value in the ClipTextproperty w ill be saved.

Text A Stringvalue containing the value that is displayed in the control w hile the control has the focus.

Table 8-4

M ask Characters

Character Description

# A required num eric character.

. A decim al point indicator as defined in Window s. It is treated as a literal.

, A thousands separator as defined in Window s. It is treated as a literal.

/ A date separator as defined in Window s. It is treated as a literal.

: A tim e separator as defined in Window s. It is treated as a literal.

\ Treat the next character as a literal.

& A character placeholder.

> Convert the follow ing characters to uppercase.

< Convert the follow ing characters to low ercase.

A A required alphanum eric character.

A An optional alphanum eric character.

9 An optional num eric character.

C Sam e as & (ensures com patibility w ith Microsoft Access).

? A required alphanum eric character.

Other Any other character is treated as a literal.

Creating an input mask

(12)

Table 8-5

Sample M asks

Input M ask Description

(# # # ) # # # -# # # # A telephone num ber.

# # # # -# # # # -# # # # -# # # # A credit card num ber.

# # # -# # -# # # # A social security num ber.

> A< AAAAAAAA A nam e field w ith the first character alw ays in uppercase and the follow ing characters alw ays in low ercase.

> AAAAAAAAAA A nam e field w ith all characters converted to uppercase.

?# :# # A tim e value.

# # / # # / # # A date value.

The mask didn’t work: Just because you use an input m ask to ensure the input is in the proper form at doesn’t m ean that the value entered w ill alw ays be correct. For instance, som eone could enter (000) 000-0000 as a telephone num ber or they could enter 99/ 99/ 99 as a date. Both of these values are invalid, yet they m eet the requirem ents specified by the input m ask. In these cases, you can use the Validate event or another control, such as the DateTimePicker, to ensure that the user’s data is correct.

As the user enters c harac ters into the c o ntro l at runtime, eac h c harac ter is validated against the input mask. Any literal c harac ters are fro zen o n the sc reen and are auto -matic ally skipped o ver. If the user enters a c harac ter that isn’t c o mpatible with the input mask, it is igno red, unless yo u have c o ded the ValidateErrorevent. Then the event will be fired and yo u c an respo nd in whatever fashio n yo u wish.

A real multimedia solution: I like to use the full m ultim edia capabilities of a PC/ XT to let the user know that they typed an invalid character in the Masked Editcontrol. Therefore, in the ValidateErrorevent, I’ll include a Beep state-m ent to generate an audible signal to the user.

Prompting the user

A pro mpt c harac ter c an be defined using the PromptCharpro perty. This c harac ter will be displayed in the eac h po sitio n o f the field where the user is expec ted to enter a value. Generally, yo u will want to use the undersc o re ( _ ) c harac ter as the pro mpt c harac ter, but yo u may want to supply a value like a zero o r a spac e depending o n the input mask. Fo r instanc e, if yo u set PromptCharto 0 and Mask to ###-##-####,

(13)

the user will see 000-00-0000 in the field. The user wo uld then o vertype the pro mpt c harac ters with the appro priate values. No te that if yo u use a value fo r PromptChar that is also legal in the input mask, then yo u need to set the AllowPromptpro perty to TRUE.

Database considerations

When using the Masked Editc o ntro l as a bo und c o ntro l, yo u need to dec ide whic h value yo u want to sto re in the database. If yo u set the PromptIncludepro perty to TRUE, the value in Textpro perty, whic h will inc lude any literal values fro m the input mask, will be saved in the database. Otherwise, the value fro m the ClipText pro perty will be used.

Using the DateTimePicker Control

While yo u c an use the TextBoxo r the Masked Editc o ntro ls to enter date and time values, using the DateTimePickerc o ntro l is a muc h b etter way. The so le purpo se o f the DateTimePickerc o ntro l is to help users enter legal date and time values. Fro m a pro gramming po int o f view, it wo rks just like a TextBoxc o ntro l. Yo u c an use the standard data b inding pro perties to c o nnec t it to yo ur datab ase.

Key properties

The DateTimePickerc o ntro l c o ntains all o f the standard pro perties fo und in an average Ac tiveX c o ntro l, suc h as Top, Left, Width, Height, Enabled, ToolTipText, etc . Ho wever, there are a few key pro perties that affec t the way the c o ntro l wo rks (see Table 8-6).

Table 8-6

Key Properties of the DateTimePicker Control

Property Description

CalendarBackColor A Longvalue containing the background color of the calendar.

CalendarForeColor A Longvalue containing the foreground color of the calendar.

(14)

Table 8-6

(continued)

Property Description

CalendarTitleBackColor A Longvalue containing the background color of the calendar’s title bar.

CalendarTitleForeColor A Longvalue containing the foreground color of the calendar’s title bar.

CalendarTrailingForeColor A Longvalue containing the foreground color for the dates before and after the current m onth.

CheckBox A Booleanvalue. When TRUE,a check box w ill be displayed next to the value. If not checked,

NULLw ill be returned as Value.

CustomFormat A Stringvalue containing an alternate form at to display date and/ or tim e values chosen from the characters listed in Table 8-7. Also, you m ust set Form at to dtpCustom(3).

Day A Variantvalue containing the currently selected day of m onth.

DayOfWeek A Variantvalue containing the currently selected day of w eek.

Format An enum erated type specifying the standard or custom form at that w ill be used to display the date and/ or tim e value. Possible values are

dtpLongDate(0) to display a date in a long form at; dtpShortDate(1) to display a date in a short form at; dtpTime(2) to display the tim e; and dtpCustom(3) to display the value using the form at string in CustomFormat.

Hour A Variantvalue containing the currently selected hour.

MaxDate A Datevalue containing the m axim um date value a user can enter.

MinDate A Datevalue containing the m inim um date value a user can enter.

Minute A Variantvalue containing the currently selected m inute.

(15)

Property Description

Second A Variantvalue containing the currently selected second.

UpDown A Booleanvalue w hen TRUEdisplays an updow n (spin) button to m odify dates instead of a drop-dow n calendar.

Value A Variantvalue containing the currently selected date.

Year A Variantvalue containing the currently selected year.

Table 8-7

M ask Characters

Character Description

D Displays the day of m onth w ithout a leading zero (1-31).

dd Displays the day of m onth as tw o digits using a leading zero if necessary (01-31).

ddd Displays the day of w eek as a three-character abbreviation ( Sun, Mon, etc.) .

dddd Displays the day of w eek w ith its full nam e (Sunday, Monday, etc.).

H Displays the hour w ithout a leading zero (0-12).

hh Displays the hour w ith tw o digits, using a leading zero if necessary (00-12).

H Displays the hour in 24-hour form at w ithout a leading zero (0-23).

HH Displays the hour in 24-hour form at, using a leading zero if necessary (00-23).

M Displays the m onth w ithout a leading zero (1-12).

M M Displays the m onth as tw o digits, using a leading zero if necessary (01-12).

M M M Displays the m onth as a three-character abbreviation (Jan, Feb, etc.).

M M M M Displays the m onth w ith its full nam e (January, February, etc.).

m Displays the m inutes w ithout a leading zero (0-59).

(16)

Table 8-7

(continued)

Character Description

m m Displays the m inutes as tw o digits, using a leading zero if necessary (00-59).

s Displays the seconds w ithout a leading zero (0-59).

ss Displays the seconds as tw o digits, using a leading zero if necessary (00-59).

t Displays AM or PM as a single character (A or P).

tt Displays AM or PM as tw o characters (AM or PM).

x Uses the Callback events (CallbackKeyDown, Format, and

FormatSize) to get the inform ation needed to form at the custom date/ tim e value.

y Displays the day of year (1-365).

yy Displays the year as a tw o-digit num ber (00-99).

yyyy Displays the year as a four-digit num ber (0100-9999).

Choosing a user interface

The DateTimePickerc o ntro l has two different ways to allo w users to edit date and time values. If yo u want to edit o nly date values, yo u c an display a dro p-do wn c alendar, whic h allo ws the user to selec t a partic ular date ( see Figure 8-4) . Set UpDownto TRUE.

Figure 8-4: Using a drop-dow n calendar to enter a date

(17)

Figure 8-5: Entering a date and tim e value

Using the DataCombo Control

The DataComboc o ntro l lo o ks and wo rks just like a regular ComboBoxc o ntro l, exc ept that the data fo r the c o ntro l c o mes direc tly fro m the datab ase. This c o n-tro l is extremely useful when yo u want to translate a c o ded data value into its text eq uivalent. It uses two datab ase tab les: o ne tab le c o ntaining the data yo u want to edit, and a translatio n tab le that c o ntains b o th the enc o ded and translated values. The b eauty o f this c o ntro l is that no c o de is req uired to perfo rm the translatio n pro c ess.

They come in pairs:The DataListcontrol is very sim ilar to the DataCombo con-trol, in the sam e w ay a list box is the sam e as a com bo box. Thus, they share m any com m on properties and m ethods.

Key properties

The DataComboc o ntro l has a number o f pro perties that affec t the way the c o ntro l wo rks ( see Table 8-8) . It also suppo rts all o f the standard pro perties, metho ds, and events listed.

Table 8-8

Key Properties of the DataCombo Control

Property Description

BoundColumn A Stringvalue that contains the nam e of the colum n that w ill supply that value to the control.

BoundText A Stringvalue that contains the current value of the

BoundColumn.

DataBindings An object reference to a DataBindingscollection.

ListField A Stringvalue that contains the nam e of the colum n used to fill the drop-dow n list.

MatchedWithList A Booleanvalue that indicates the contents of the BoundText

m atches one of the entries in the list.

Continued

(18)

Table 8-8

(continued)

Property Description

MatchEntry An enum erated data type that controls how the user’s keystrokes w ill be m atched w ith the values in the control. A value of dblBasicMatching(0) m eans that w hen the user presses a key, the list of values is searched for by the first item w hose first character m atches the key that w as pressed. If the sam e key is pressed again, the second item w hose first character m atches w ill be displayed. A value of dblExtendedMatching

(1) m eans that the control w ill search for an item in the list w hose value m atches all of the characters entered. Typing additional characters refines the search.

RowMember A Stringvalue that identifies w hich set of data should be used w hen a RowSourcehas m ore than one set of data.

RowSource An object reference to an object that can act as a data source. Com m on data sources include the ADO Data Control, a

Recordsetobject, or a Class m odule w here the

DataSourceBehaviorproperty is set to vbDataSource(1).

SelectedItem A Variantvalue containing a bookm ark for the currently selected record.

Style An Integervalue that controls how the user interacts w ith the control. Values are dbcDropdownCombo(0), w hich allow s the user to enter a value in the text box or select a value from the drop-dow n box; dbcSimpleCombo(1), w hich allow s the user to enter a value into the text box or select a value from the list below the text box; and dbcDropdownList(3), w hich allow s the user to only select a value from the drop-dow n list.

Sort, please:You should use a Select statem ent w ith the Order Byclause w hen defining your data source so that the list of values can be displayed in sorted order.

Key methods

The DataComboc o ntro l suppo rts the usual asso rtment o f metho ds; ho wever, the ReFillmetho d is unique to this and the DataListc o ntro l.

(19)

DataCombo

.ReFill ( )

The ReFillmetho d gets a fresh c o py o f the data fro m the RowSourceand rec re-ates the list o f items in the list.

It’s not the same:Don’t confuse the ReFillm ethod w ith the Refreshm ethod. The Refreshm ethod m erely repaints the data on the screen. It doesn’t get a fresh copy of the data from the database.

Configuring the control

Using the DataComboc o ntro l is mo re c o mplic ated than mo st bo und c o ntro ls, bec ause it needs to interac t with two database tables. It also c an be used in two dif-ferent fashio ns. First, the user may c ho o se a value fro m a list o f values. Sec o nd, the user may c ho o se fro m a list o f values that are auto matic ally enc o ded and dec o ded as needed.

Selecting from a list

To func tio n as a no rmal b o und c o ntro l, yo u need to spec ify values fo r b o th the DataSourceand DataFieldpro perties. The DataSourcepro perty must c o ntain an o b jec t referenc e to an OLE DB data so urc e suc h as an ADO Data Controlo r a Recordseto b jec t that referenc es the tab le yo u want to update. The DataField pro perty spec ifies the c o lumn name who se value is displayed in the text part o f the c o mb o b o x.

The list part o f the c o mbo bo x is po pulated using the RowSourceand ListField pro perties. The RowSourcepro perty is an o bjec t referenc e to an ADO Data Control o r a Recordseto bjec t c o rrespo nding to the list o f entries to be displayed in the list part o f the c o mbo bo x. The ListFieldpro perty c o ntains the name o f the c o lumn who se values will be displayed in the list part o f the c o ntro l. Befo re yo u c an use the DataComboc o ntro l, yo u need to set o ne mo re pro perty, BoundColumn. This pro perty sho uld be set to the same value as ListField.

Translating a value

When designing a datab ase it is c o mmo n to co difya value in o rder to reduc e redundanc y in yo ur datab ase. When yo u do this, yo u typic ally c reate a field c alled Manufac turerId in o ne tab le and use ano ther tab le to translate Manufac turerId into the manufac turer’s Name. Thus the Manufac turerId value is kno wn as the

co difie dvalue, while Name is kno wn as the translate dvalue.

(20)

In the example used in this bo o k, eac h ro w in the Invento ry table c o ntains a referenc e to the Manufac turerId, while the Manufac turers table c o ntains Manufac turerId and the Name asso c iated with the Manufac turerId. Bec ause Manufac turerId is a numeric value, it is diffic ult to remember whic h value is asso c iated with eac h manufac turer’s name. This situatio n is an ideal c andidate fo r the DataComboc o ntro l.

The pro perties o f the DataComboc o ntro l sho uld be set as fo llo ws: DataSource= Ado dc 1 (the table with the raw data); DataField= Manufac turerId (the c o dified field in the raw data table); RowSource= Ado dc 2 (the translatio n table); ListField = Name (the translated field in the translatio n table); and BoundColumn=

Manufac turerId (the c o dified field in the translatio n table).

When using the DataComboc o ntro l to auto matic ally translate a value, yo u sho uld set the Stylepro perty to dbcDropdownList( 3) in o rder to prevent pro blems. The o ther values fo r Styleallo w the user to enter their o wn value into the c o ntro l. This c an c ause a translatio n erro r, sinc e the value in the c o dified c o lumn do esn’t have translatio n value in the translatio n table. The easiest way to handle this situatio n is to plac e a butto n beside the DataComboc o ntro l to add the new value to the transla-tio n table and then refresh the data displayed in the c o ntro l using the Refill metho d ( see Figure 8-6) .

Figure 8-6: Adding a value to the translation table

(21)

Listing 8-4:

The Command2_Click event in Inventory

Information —Add New M anufacturer form

Private Sub Command2_Click() Form1.Adodc2.Recordset.AddNew

Form1.Adodc2.Recordset.Fields(“ManufacturerId”).Value = _ CLng(Text1.Text)

Form1.Adodc2.Recordset.Fields(“Name”).Value = Text2.Text Form1.Adodc2.Recordset.Update

Form1.Adodc2.Recordset.Requery Form1.DataCombo1.ReFill

Form1.DataCombo1.Text = Text2.Text Unload Me

End Sub

Thoughts on Reducing Data Errors

If you w ere to w rite a database program in a different program m ing language, you w ould probably have to spend a lot of tim e m oving data from database buffers to the various dis-play fields. In som e languages such as COBOL, you m ight spend as m uch as fifty percent of your program m ing effort w riting this type of code.

By using bound controls in Visual Basic, you can do tw o things. First, you reduce the overall size of your program , since you don’t have to m ove all that inform ation to and from the database buffers. Second, you im prove the reliability of your program , since the code that handles the data m ovem ent isn’t yours. Of course, you m ight m ake a m istake w hen speci-fying w hich field is associated w ith a particular control, but this is m uch easier to find and fix than looking through a com plex program and trying to find w hy a particular field w asn’t updated.

Data validation is a big part of the process also. The best w ay to help prevent your database from becom ing corrupt is to verify that all of the data that is entered into the database is acceptable. Using controls such as the MaskedEdit and the DateTimePicker control m eans that the data that is entered is at least of the right type and the proper form at. This goes a long w ay tow ards preventing bad data from reaching your database.

Som etim es bad data w ill get into your database no m atter how m uch you check and recheck your data before it is entered. For instance, som eone could m istype an item num -ber yet still end up w ith a bad record. Even though the item num -ber w as valid, it w asn’t the product the custom er w anted. To help prevent this type of problem , you should provide as

(22)

Summary

In this c hapter yo u learned the fo llo wing:

✦Yo u c an validate data in a bo und c o ntro l by using the Change, KeyPress, LostFocus,and Validateevents.

✦Yo u c an use the MaskEditc o ntro l to pro mpt users fo r textual info rmatio n.

✦Yo u c an use the DateTimePickerc o ntro l to help users selec t date and time values.

✦Yo u c an use the DataCombobo x in plac e o f a no rmal ComboBoxc o ntro l to allo w a user to selec t fro m a series o f values extrac ted direc tly fro m yo ur database.

Continued

m uch visual feedback as possible. Perhaps you could display a picture of the item , w hich w ould allow the custom er to see that they entered the w rong item . Izf a picture isn’t practi-cal, you should at least provide a description of the item from w hich the custom er m ay be able to recognize their m istake.

Gambar

Table 8-1Key Properties of Bound Controls
Figure 8-2: Specifying a format for your data
Table 8-2Key Properties of the StdDataFormat Object
Table 8-3Key Properties of the Masked Edit Control
+7

Referensi

Dokumen terkait

Adapun tujuan diadakannya indeks saham syariah sebagaiman Jakarta Islamic Index yang melibatkan 30 saham terpilih, yaitu sebagai tolak ukur untuk mengukur kinerja

You can download and install the soft file of this incredible book Time Mends (Timber Wolves, Book 2) By Tammy Blackwell currently and in the link offered.. Yeah, different with

Indonesia merupakan negara dengan orang muslim terbesar didunia, akan tetapi setiap ormas muslim sendiri tentunya berbeda dalam memutuskan suatu masalah baru yang muncul

54 Tahun 2010 tentang Pengadaan Barang/Jasa Pemerintah serta menindaklanjuti proses seleksi untuk Paket Pekerjaan Pengadaan Meubelair (985 Unit) , bersama ini kami

Additionally, Aaron developed a wide variety of exercises and stretches specific for posture and alignment based on the personal needs and desires of the many clients he has served

n salinannya sebagaimana tertuang dalam lam proses pembuktian kualifikasi

Uang merupakan uang milik masyarakat atau uang beredar di masyarakat (di luar Bank Sentral seperti Bank Indonesia dan perbankan atau semua bank), yang terdiri dari :.. Uang Kertas

Puji syukur kami panjatkan kepada Tuhan Yang Maha Esa atas limpahan rahmat dan hidayah-Nya sehingga Prosiding Seminar Nasional MIPA Universitas Negeri Yogyakarta