VB.NET  •  Retrieve the Contacts

Listing 3. RetrieveContacts provides a common function to get a list of contacts from the local SQL CE database. Notice that the properties and methods for a SQL CE database operation (SqlCeCommand, SqlCeDataAdapter) are similar to their SQL Server counterparts.

Public Function RetrieveContacts() As String
Dim ds1 As New DataSet
Dim strMessage As String = ""
Dim objCommand As SqlCeCommand
Dim drRow As DataRow

' Check to see if you have a cached data adapter
If _daDataAdapter Is Nothing Then
strMessage = InitializeDataAdapter()
End If
' Check for an error initializing the data adapter to 
' the local DB
If strMessage <> "" Then
Return strMessage
Else
Try
' Get a database connection first
Dim objSqlCon As SqlCeConnection
objSqlCon = InitializeDBConnection()
If Not (objSqlCon Is Nothing) Then
' Open the database connection
objSqlCon.Open()

' Open the local DB and retrieve all records into the 
' dataset
_daDataAdapter.SelectCommand.Connection = objSqlCon
_daDataAdapter.Fill(ds1, "Contacts")
_dsContacts = ds1

' Quickly close the database connection
objSqlCon.Close()
End If
Catch ex As SqlCeException
' Error handling code here
End Try
End If
Return strMessage
End Function