LogoASPAlliance: Articles, reviews, and samples for .NET Developers
Creating AJAX Enabled Multi Keyword Database Search Engine
by Habiburahman Khaled
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 39948/ 70


This article will show you how to develop a simple multi-column, multi-keyword, and multi option search engine; it can be used for any database driven application that requires search engine facility.

Figure 1

It is worth mentioning that at the time I was writing this article I found Kelly Gafford single column, multi-word database search sample code at planetsourcecode written in Classic ASP very useful which gave me the idea of how to go ahead.

Application features

This application is equipped with the following features:

·         Search for multiple keywords, separated either by comma, space, or +.

·         Search in multiple columns.

·         Different search options like All, Exact, or any.


·         Microsoft SQL Server 2005/SQL Server 2005 Express

·         .NET Framework 2.0 or later

·         Microsoft AJAX Extensions

·         IIS


The database used for the article is Northwind and it is hoped that users are acquainted and furnished with it. Those who do not have Northwind can get one from here.

Listing 1: Create the following View in your Database

CREATE VIEW [dbo].[CustomersView]
SELECT CustomerID, CompanyName, ContactName, 
 ContactTitle, City, Country, Address, 
 ISNULL(CompanyName, '') + ' ' + ISNULL(ContactName, '') + 
 ISNULL(ContactTitle, '') + ' ' + 
 ISNULL(City, '') + ' ' + ISNULL(Country, ''AS FullDescription
FROM dbo.Customers

The code in listing 1 is self descriptive; CustomerView has been created based on the Customers Table. A virtual column named FullDescription is added to the view which combines multiple columns into one.

There are two methods for searching multiple columns in the database table:

1.    To create a virtual column in view or stored procedure and use the + operator in SQL Server, CONCAT or CONCAT_WS in MySQL, and/or ||,CONCAT in ORACLE to combine the data into one.

2.    To use AND or OR logical operator for each single column that we are searching in.

In this article both of the above methods are used.

Listing 2: Part of Customer.aspx page

<form id="form1" runat="server">
    <div id="HeaderDiv" class="Header">
        <h1>Search for Customers in Northwind Database</h1>
    <div id="ContentDiv" class="Content">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <div id="SearchControls" class="SearchControls">
            <asp:TextBox ID="SearchTextBox" runat="server" />
            <asp:DropDownList ID="SearchCriteriaList" runat="server">
                <asp:ListItem Selected="True" Value="AND">All</asp:ListItem>
                <asp:ListItem Value="OR">Any One</asp:ListItem>
                <asp:ListItem Value="Exact">Exactly</asp:ListItem>
            <asp:Button ID="BtnSearch" runat="server" Text="Search" 
              OnClick="BtnSearch_Click" />
            <div style="text-align:center"> 
            <asp:UpdateProgress ID="UpdateProgressControl" runat="server">
                    <img src="images/spinner.gif" alt="loading.." />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <asp:Label ID="RecordCount" runat="server" 
                        EnableViewState="False" Font-Bold="True"
                        Font-Size="Medium" Visible="False"></asp:Label>
                <asp:GridView ID="CustomersGridView" runat="server" 
             <asp:BoundField DataField="CompanyName" HeaderText="Company Name" />
             <asp:AsyncPostBackTrigger ControlID="BtnSearch" EventName="Click" />
    <div id="ErrorDiv" runat="server">

The code in listing 2 shows the aspx page which resides all the controls used for the search application. This is not the complete page, it just shows you the controls and AJAX coding.

A Complete application can be downloaded from the download section.

Listing 3: The doSearch method

private void doSearch(string InputKeyword, string SelectCriteria)
  //define objects
  string strSQL;
  SqlConnection conn;
  SqlCommand command;
  SqlDataReader reader;
  if (SelectCriteria == "Exact")
    strSQL = "SELECT  CustomerID, CompanyName," +
      "ContactName, ContactTitle, City," +
      "Country, Address FROM CustomersView WHERE (FullDescription LIKE '%";
    strSQL = strSQL + InputKeyword + "%')";
//Define an array list and then assign User Enterd 
//information separated by "+",","," "
    String[]SearchArrayList = InputKeyword.Split(new Char[]
      '+', ' ', ','
    , StringSplitOptions.RemoveEmptyEntries);
    strSQL = "SELECT  CustomerID, CompanyName, ContactName," +
      "ContactTitle, City, Country, Address FROM CustomersView WHERE";
    String strJoin = string.Join("%') " + SelectCriteria +
      " (FullDescription LIKE '%", SearchArrayList);
//if you want to add another column to the search criteria 
//in place of using Virual Column
/* String strJoin2 = string.Join("%') " + SelectCriteria + 
  " (Country LIKE '%", SearchArrayList);
strSQL = strSQL + " ((ProductName LIKE '%" + strJoin + "%')" + "OR" + 
  "(Country LIKE '%" + strJoin2 + "%'))";*/
    strSQL = strSQL + " (FullDescription LIKE '%" + strJoin + "%')";
  //read the connection from web.config file
  string ConnStr =
  //Intialize connection
  conn = new SqlConnection(ConnStr);
  // intialize command object
  command = new SqlCommand(strSQL, conn);
    //open connection
    //Intialize reader
    reader = command.ExecuteReader();
    //assign reader to Gridview datasource
    CustomersGridView.DataSource = reader;
    //Bind the data to Gridview
    //Display the number of record found
    RecordCount.Text = "Your search for: <span style=color:blue>" +
      InputKeyword.ToString() + "</span>" + " Found " +
      CustomersGridView.Rows.Count.ToString() + " Matches";
    // close reader
  catch (SqlException exception)
    ErrorDiv.InnerHtml = "Error!" + "<br/>" + exception.Message;
    //close connection

The code in Listing 3 defines the doSearch method which is located in the code-behind file of the aspx page that takes two parameters, the first one specifies user entered information in the search box, and the second one specifies the search option it could be either AND(All), OR(Any), or Exact(Exactly).

Listing 4: If you would like to add more fields to the search criteria use the following code

String strJoin2 = string.Join("%') " + SelectCriteria + 
    " (Country LIKE '%", SearchArrayList); 
 strSQL = strSQL + " ((ProductName LIKE '%" + strJoin + "%')" + 
    "OR"+"(Country LIKE '%" + strJoin2 + "%'))";

Listing 5: Calling the doSearch method from a button click event

protected void BtnSearch_Click(object sender, EventArgs e)
  //make sure that user enter something for search
  if (SearchTextBox.Text.Length != 0)
   /*Block current thread for 1 second in order to see the spinner in AJAX
   progress control */
    string strCriteria = SearchCriteriaList.SelectedItem.Value;
    doSearch(SearchTextBox.Text.Trim(), strCriteria);
    RecordCount.Visible = true;

The code in Listing 5 is calling the doSearch method from a button click event which takes values of a textbox named SearchTextBox, and dropdown list named SearchCriteriaList.

The Sleep method of Thread object is called to block the current thread for one second so the user can see the spinner image in AJAX progress control.

What is happening in the background?

When you use the doSearch method you can see what is happening in the background. Below is a trace from Visual Studio 2005 in debug mode.

After entering maria+berlin in the search box and hitting the search button we have the following values for strJoin and strSQL.

Figure 2

First, it is splitting the values separated by comma, plus, or spaces and then it assigns each of those values into the LIKE operator of SQL.


In this article you have learned how to create an AJAX enabled database search engine and you have see how effective it is to use the String.Split, and String.Join methods of the C# language. You have also learned how to search for any, all, or exact phrases in the database tables.

©Copyright 1998-2021  |  Page Processed at 2021-11-26 6:03:18 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search