ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Render images in autocomplete list of ASP.Net AJAX AutoCompleteExtender
Author Name: Mudassar Khan Published Date: February 06, 2010
Filed Under :
ASP.Net
 |
AJAX
Views: 2347
In this article I am explaining, how to display images in the AutoComplete List in ASP.Net AJAX Control toolkit AutoCompleteExtender Control in ASP.Net
 
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(Of String)
        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

ASP.Net AJAX  AutoCompleteExtender With Images in ASP.Net

The above code has been tested in the following browsers

Internet Explorer  FireFox  Chrome  Safari  Opera 

* 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


If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

Related Articles

Comments

Avi said:
I am getting the error... AjaxControlToolkit.AutoCompleteExtender does not have a public property named OnClientPopulated.br br how to over come this
February 07, 2010  

Mudassar Khan said:
Reply To: Avi
You are using older version of Toolkit. Either download from the link given in article or download the sample attached.
February 07, 2010  

Abhishek Bhatnagar said:
i think u store path of the image in the database and fatch the image with help of this java script function . i am right or wrong.
February 08, 2010  

Mudassar Khan said:
Reply To: Abhishek Bhatnagar
Photos are stored on disk and not database
February 08, 2010  

anant jha said:
we just need to store image name without extension in database(eg- sunset for sunset.jpeg).Rest the code will do.and the folder name is photos in the above code where we are saving our photos.br Great matter.Thanks a lot Mudassar Khan.
March 15, 2010  

Arpit Mathur said:
my code is not giving any error but doesnt provide any output.br
March 23, 2010  

Mudassar Khan said:
Reply To: Arpit Mathur
Download the sample and check what you are missing
March 24, 2010  

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code