VB.NET  •  The doQuery Function Does the Work

Listing 2. The doQuery function calls the Google search engine, then formats the results that come back using String.Format and the string specified in the GoogleBox tag's StringFormat property. Each item is added to a StringBuilder list, which is then converted to a string when doQuery returns.

Private Function doQuery() As String
   Dim i As Int32
   Dim max As Int32
   Dim displayTitle As String
   Dim sb As StringBuilder = New StringBuilder()

   ' create a Google Search object
   Dim s As GoogleSearchService = _
      New GoogleSearchService()

   ' invoke the search method
   Dim r As GoogleSearchResult = _
      s.doGoogleSearch( _
      _key, _query, 0, _maxResults, False, _
      "", False, "", "", "")

   ' get the number of results returned
   max = r.resultElements.GetUpperBound(0)

   ' loop through formatting each result
   For i = 0 To max
      ' if the title for this result is blank
      ' use the URL instead
      If (r.resultElements(i).title <> "") Then
         displayTitle = r.resultElements(i).title
      Else
         displayTitle = r.resultElements(i).URL
      End If
      ' format this result line
      sb.Append(String.Format(_formatString, _
            (i + 1), displayTitle, _
            r.resultElements(i).URL, _
            r.resultElements(i).snippet))
   Next i

   ' return the formatted result list
   doQuery = sb.ToString()
End Function