When websites feature a text search and a table or list of results you will sometimes see something like:

73 records matched your search or 128 matches found.

This is actually very easy to do but incredibly hard to find an easy way of doing it. Here’s how it’s done.

This example is based on searching a company contact list.

Firstly, in your web form you need your DataSource and SelectCommand, for example:

<asp:SqlDataSource ID=”srcResults” runat=”server” ConnectionString=”<%$ ConnectionStrings:constrConnectionString %>” SelectCommand=”SELECT * FROM [contacts] WHERE [firstname] LIKE ‘%’ + txtSearch + ‘%’ OR [lastname] LIKE ‘%’ + txtSearch + ‘%’”>

Then, in your VB you get the number of records returned as follows:

Dim intMatches As Integer
Dim dv As Data.DataView
dv = CType(srcResults.Select(DataSourceSelectArguments.Empty), Data.DataView)
intMatches = dv.Count.ToString()

You will need to change srcResults in the third line to the ID of your DataSource control, the rest of the code can stay as it is.

Finally, you need to output the number of records to the page. This can be done by putting a Literal or Label control in the web form:

<asp:Literal ID=”litRecordCountText” runat=”server” />

Here’s some code which gives different output depending on whether there are 0, 1 or more than 1 record counted:

If intMatches = 0 Then
litRecordCountText.Text = “<span style=’color:’cc0000′>Sorry, no contacts matched your search text.<br />Try entering just the first few letters of a name.</span>”
ElseIf intMatches = 1 Then
litRecordCountText.Text = “1 match found. The following contact matches your search.”
Else
litRecordCountText.Text = intMatches & ” matches found. The following contacts match your search.”
End If