19.12.2012 Views

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

If a Find method does not locate a record matching the criteria, the first or last record<br />

(depending on where the search is heading) in the recordset becomes the current record <strong>and</strong><br />

the NoMatch property is set to True. Therefore, the following lines of code can be used to<br />

keep the current record current whenever the Find method is unsuccessful.<br />

BkMk = Data1.Recordset.Bookmark<br />

Data1.Recordset.FindNext criteria<br />

If Data1.Recordset.NoMatch = True Then<br />

Data1.Recordset.Bookmark = BkMk<br />

End If<br />

EXAMPLE 2<br />

The following program displays the large cities in a country specified by the user. Due to the SQL statement<br />

in the setting for datCities.RecordSource, the cities will be presented alphabetically. Notice the h<strong>and</strong>ling<br />

of the string variable criteria. Had the Find statement been<br />

datCities.Recordset.FindFirst “country = nom”<br />

the error message “Can’t find name ‘nom’.” would have been generated.<br />

Object Property Setting<br />

frmDBMan Caption EXAMPLE 12-2-2<br />

lstCities<br />

cmdFind Caption Find Cities<br />

lblCountry Caption Country<br />

txtCountry Caption (blank)<br />

datCities Caption Large World Cities<br />

Database MEGACTY2.MDB<br />

Name<br />

Record SELECT * FROM<br />

Source Cities ORDER BY<br />

city ASC<br />

Private Sub cmdFind_Click()<br />

Dim nom As String, criteria As String<br />

lstCities.Clear<br />

If txtCountry.Text “” Then<br />

nom = txtCountry.Text<br />

criteria = “country = ” & “‘” & nom & “‘”<br />

datCities.Recordset.FindFirst criteria<br />

Do While datCities.Recordset.NoMatch = False<br />

lstCities.AddItem datCities.Recordset.Fields(“city”).Value<br />

datCities.Recordset.FindNext criteria<br />

Loop<br />

If lstCities.ListCount = 0 Then lstCities.AddItem “None”<br />

Else<br />

MsgBox “You must enter a country.”, , “”<br />

txtCountry.SetFocus<br />

End If<br />

End Sub<br />

[Run, type China into the text box, <strong>and</strong> press the comm<strong>and</strong> button.]<br />

Relational Databases <strong>and</strong> SQL 337

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!