Auto Complete with images

Database
For this tutorial I am making use of Employees table of Microsoft’s NorthWind database. You can download the NorthWind database using the link below

Download Northwind Database

 
Connection String
Below is the connection string to the database which I have placed in the web.config.
<connectionStrings>
      <addname=”constr”connectionString=”Data Source = .\SQLExpress;       
       Initial Catalog = Northwind; Integrated Security = true”/>
</connectionStrings>
 
AJAX Control Toolkit
Download the AJAX Control Toolkit DLL using the link below and add reference to your project.

Download AJAX Control Tookit

 
Once that’s done register it on the ASPX page as given below
<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”cc1″ %>
 
HTML Markup
Below is the HTML markup of the ASP.Net Web Page
<asp:ScriptManager ID=”ScriptManager1″ runat=”server”
EnablePageMethods = “true”>
</asp:ScriptManager>
 
<asp:TextBox ID=”txtContactsSearch” runat=”server”></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod=”SearchEmployees”
    MinimumPrefixLength=”1″
    CompletionInterval=”100″ EnableCaching=”false” CompletionSetCount=”10″
    TargetControlID=”txtContactsSearch” OnClientPopulated =    “Employees_Populated”
    OnClientItemSelected = ” OnEmployeeSelected”
    ID=”AutoCompleteExtender1″ runat=”server” FirstRowSelected = “false”>
</cc1:AutoCompleteExtender>
 
As you can notice above I have placed a ScriptManager, a TextBox that will act as AutoComplete and the ASP.Net AJAX Control Toolkit AutoCompleteExtender. Also I am calling a method SearchEmployees using the ServiceMethod property. I have also specified two client side events in order to display images which I’ll be explaining later.
 
Server Side Methods
The following method is used to populate the Auto complete list of employees
C#
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchEmployees(string prefixText, int count)
{
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager
                .ConnectionStrings[“constr”].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = “select EmployeeId, FirstName, LastName from” +
             ” Employees where FirstName like @SearchText + ‘%'”;
            cmd.Parameters.AddWithValue(“@SearchText”, prefixText);
            cmd.Connection = conn;
            conn.Open();
            List<string> employees = new List<string>();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    employees.Add(AjaxControlToolkit.AutoCompleteExtender
                       .CreateAutoCompleteItem(string.Format(“{0} {1}”,
                       sdr[“FirstName”], sdr[“LastName”]),
                       sdr[“EmployeeId”].ToString()));
                }
            }
            conn.Close();
            return employees;
        }
    }
}
 
VB.Net
<System.Web.Script.Services.ScriptMethod(), _
    System.Web.Services.WebMethod()> _
Public Shared Function SearchEmployees(ByVal prefixText As String, ByVal count As Integer) As List(OfString)
        Dim conn As SqlConnection = New SqlConnection
        conn.ConnectionString = ConfigurationManager _
         .ConnectionStrings(“constr”).ConnectionString
        Dim cmd As SqlCommand = New SqlCommand
        cmd.CommandText = “select EmployeeId, FirstName, LastName from ” & _
        ” Employees where FirstName like @SearchText + ‘%'”
        cmd.Parameters.AddWithValue(“@SearchText”, prefixText)
        cmd.Connection = conn
        conn.Open()
        Dim employees As List(Of String) = New List(Of String)
        Dim sdr As SqlDataReader = cmd.ExecuteReader
        While sdr.Read
            employees.Add(AjaxControlToolkit.AutoCompleteExtender _
            .CreateAutoCompleteItem(String.Format(“{0} {1}”, _
             sdr(“FirstName”), sdr(“LastName”)), sdr(“EmployeeId”).ToString()))
        End While
        conn.Close()
        Return employees
End Function

 

The above method simply searches the customers table and returns the list of employee’s names that matches the prefix text. I am also embedding the employee Id using the AutoCompleteExtender Item of ASP.Net AJAX Control Toolkit AutoCompleteExtender Control
This is later used Client Side for displaying images of Employees
For more information on using AJAX Control Toolkit AutoCompleteExtender Control in ASP.Net refer the following article

ASP.Net AJAX Control Toolkit AutoCompleteExtender without using Web Services

 
Client Side Methods
Below methods are used to embed images in the AutoCompleteList of ASP.Net AJAX Control Toolkit AutoCompleteExtender Control
<script type = “text/javascript”>
function Employees_Populated(sender, e) {
    var employees = sender.get_completionList().childNodes;
    for (var i = 0; i < employees.length; i++) {
        var div = document.createElement(“DIV”);
        div.innerHTML = “<img style = ‘height:50px;width:50px’ src = ‘photos/”
        + employees[i]._value + “.jpg’ /><br />”;
        employees[i].appendChild(div);
    }
}
function OnEmployeeSelected(source, eventArgs) {
    var idx = source._selectIndex;
    var employees = source.get_completionList().childNodes;
    var value = employees[idx]._value;
    var text = employees[idx].firstChild.nodeValue;
    source.get_element().value = text;
}
</script>
 
The Employees_Populated gets called when the AutoCompleteList is populated Client Side. This method embeds the images into the AutoComplete item.
The OnEmployeeSelected returns the text and value of the selected AutoComplete Item.
Below figure describes the working of AutoComplete Extender with images

 

The above code has been tested in the following browsers 

         

* All browser logos displayed above are property of their respective owners.

 

You can download the related source code in VB.Net and C# using the link below.

ASP.Net_AutoCompleteExtender_With_Images.zip

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s