Click here to Skip to main content
Email Password   helpLost your password?

Introduction

The purpose of this article is to show how to use the free AutoSuggestBox control to add 'Google Suggest' functionality to your ASP.NET application. There are plenty of articles available on the internet that explains how to do it, but there is usually just a lot of theory and not much code that you can easily add to your application. AutoSuggestBox encapsulates all the complex functionality and only requires developers to specify the data source for loading the auto-suggest menu.

Background

Have you seen Google Suggest? It is an application created by Google that demonstrates the power of AJAX. It is really amazing to see it for the first time, but in a little while, the notoriety wears off and most developers forget about it. While many people acknowledge its 'coolness' factor, they don�t know how to integrate it with other web applications.

The first time I saw this control, I came away with the same feeling. What an awesome idea, but I have no use for it. Several months ago, I started working on a travel application called 'Travelope' (see here). When working on the airfare search form, I was thinking of a simple interface for selecting FROM and TO locations. I considered using a combo box, but there were 1000s of cities, so the form would take a long time to load. Another option would be to use a text box with a link to popup a city lookup window. That would require users to open a reference window every time they forgot the spelling, so that would not be a great option either. I started looking at other travel sites for ideas. Many of these sites were using 'Google Suggest'-like controls for the purpose of selecting cities and airports. I thought that would be perfect for 'Travelope', too. And that was how AutoSuggestBox was born.

Using the code

What is AutoSuggestBox?

AutoSuggestBox is a custom control written in C# that makes it simple to add 'Google Suggest'-like functionality to your web applications. It supports C# and VB.NET and works in Internet Explorer as well as in Firefox. This control utilizes AJAX to retrieve data without refreshing the whole page. Developers can use CSS to adjust the look and feel of the control on the web page.

Adding AutoSuggestBox to your Web Application

Download the appropriate AutoSuggestBox package from here. There are four files that you need to add to your application to use AutoSuggestBox.

First, add a reference to 'AutoSuggestBox.dll'. Then create a sub-directory 'asb-includes' under the root of your web application. Copy the other three files into the new sub-directory.

More detailed instructions are available here.

Specify data types for loading auto-suggest menu items

When the user starts typing in the AutoSuggestBox, you need to provide a data source for the suggested values. The system allows for as many data sources as required by your application. For example, you can have one data source for the 'City' suggest box, another for the 'Airport'.

To add a data source, you need to modify the 'GetAutoSuggestData.aspx' file. By default, the class implements the "City" datasource. "LoadMenuItems" contains a switch statement for loading different types of data:

private ArrayList LoadMenuItems(string sDataType, string sKeyword) 
{
    ArrayList aMenuItems;

    switch(sDataType)
    {
        case "City":
            aMenuItems=LoadCities(sKeyword);
            break;
        default:
            throw new Exception("GetAutoSuggestData  Type '" + 
                      sDataType + "' is not supported.");
    }
    return aMenuItems;
}

The 'LoadCities' method retrieves the suggested cities from the database according to the characters typed in by the user. It loads the top 10 cities starting with a specified keyword. Then it generates an array of ASBMenuItems and fills it with the results from the database.

private ArrayList LoadCities(string sKeyword)
{
    ArrayList aOut=new ArrayList();

    string sConnString="Provider=Microsoft.Jet.OLEDB.4.0;" + 
           "Data Source=c:\\databases\\AutoSuggestBox_Demo.mdb;" + 
           "User Id=admin;Password=;";
    OleDbConnection oCn=new OleDbConnection(sConnString);

    string sSql="SELECT TOP 10 tblCity.Name as CityName, " +
                "tblCity.Code as CityCode, " +
                "tblCountry.Name as CountryName, " +
                "tblState.Name as StateName " + 
                " FROM (tblCity INNER JOIN tblCountry" + 
                " ON tblCity.CountryID=tblCountry.ID) " +
                " LEFT OUTER JOIN tblState" + 
                " ON tblCity.StateID=tblState.ID " + 
                " WHERE (tblCity.Name LIKE '" + 
                sKeyword.Replace("'", "''") + "%') " +
                " ORDER BY tblCity.Name";

    OleDbCommand oCmd = new OleDbCommand(sSql, oCn);
    oCn.Open();

    OleDbDataReader oReader = oCmd.ExecuteReader();

    string sCity;
    string sCityCode;
    string sState;
    string sCountry;
    
    string sLabel;

    ASBMenuItem oMenuItem;

    while (oReader.Read())
    {
        //Build label using City, Country & State

        sCity        =oReader.GetString(0);
        sCityCode    =oReader.GetString(1);
        sCountry    =oReader.GetString(2);

        if (oReader.GetValue(3)==System.DBNull.Value)
            sState="";
        else
            sState=oReader.GetString(3);
        

        sLabel=sCity;
        
        //Append either state or country

        if (sState != "")
            sLabel+=", " + sState;
        else
            sLabel+=", " + sCountry;
        
        oMenuItem=new ASBMenuItem();
        oMenuItem.Label=sLabel;
        oMenuItem.Value=sCityCode;
        
        aOut.Add(oMenuItem);
    } 

    oReader.Close();
    oCn.Close();

    return aOut;
}

If you need to add other data sources, just add more case statements to the LoadMenuItems function.

Insert the AutoSuggestBox control into a web form

  1. Create or open an already existing web form.
  2. Add the following line to the top of your ASPX page:
    <%@ Register TagPrefix="Custom" Namespace="ASB" Assembly="AutoSuggestBox" %>
  3. Add the following line to the location where you want the suggest box to appear:
    <Custom:AutoSuggestBox id="Control ID" 
             DataType="Supported Data Type" runat="server" 
             CssClass="Text Box Style" 
             MaxLength="Max chars in TextBox" 
             Columns="Num of visible chars"/>

    For example:

    <Custom:AutoSuggestBox id="asbCity" DataType="City" 
                runat="server" CssClass="FormCtrlStyle" 
                MaxLength="100" Columns="30"/>
  4. Make sure that value of the DataType attribute has been implemented in 'GetAutoSuggestData.aspx.cs'. See the previous section.
  5. If your web application doesn't run in the root of the webserver (e.g. http://localhost/WebApp), then you need to add another attribute to the AutoSuggestBox tag:
    <Custom:AutoSuggestBox id="asbCity" 
             DataType="City" runat="server" CssClass="FormCtrlStyle" 
             MaxLength="100" Columns="30" 
             ResourcesDir="/WebApp/AutoSuggestBox"/>

    Note: By default, the ResourcesDir is "/asb_includes".

How Does it Work

When the user starts typing text in the control, JavaScript handles the OnKeyUp, OnKeyDown and OnKeyPress events. Then, AJAX is used to contact the server side with every click, to retrieve a list of suggested entries.

So the flow of events is as follows:

  1. The user presses a key while the focus is on the AutoSuggestBox control.
  2. JavaScript checks if the user entered up/down/enter or any other character.
  3. If the user typed an alphanumeric character, JavaScript sends the XmlHttpRequest to the GetAutoSuggestData page on the server.
  4. The page 'GetAutoSuggestData.aspx' takes the current value of the text box and the type of data to retrieve. It usually generates a query to retrieve suggested values from the database. Then it uses the results of the query to create the HTML for the suggest menu and returns it back to the page.
  5. The web page retrieves the updated 'Suggest Menu' and displays it in place of the old one.

Conclusion

In this article, we demonstrated how simple it is to add 'Google Suggest' functionality to your web applications using the free AutoSuggestBox control.

Happy programming!!!

Points of Interest

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Questionmaking the items appear on top infornt of other controls
svknair
22:04 26 Jun '09  
its reallya good feature but i need some modifications in display
i made changes to css but its causing autopostback

in css
.asbmenu i added
overflow:auto;
height:80px;

so that i can limit the dropdown to a particular height & give scroll bar
but the problem is if i scroll for viewing the next item it causes postback & the dropdown gets hidden

i need to add scroll bar & limit the height of the dropdown as when the items in the dropdown are more they aappear behind other controls
i tried changing the z-index but nothing changed


any solution on this
Generalnot working...
Member 3971891
20:52 16 Dec '08  
I am getting the following error while running this code--

Could not load type 'ASB.GetAutoSuggestData'. G:\AutoSuggestBox_Demo\asb_includes\GetAutoSuggestData.aspx

pls tell me how to solve dis prblm & run thiss application. kindly reply me on my following E mail ID pls..

shalabh.dixit@gmail.com

thnx & regards,
Shalabh Dixit
GeneralThis is really good
darlasrikanth
23:01 27 Nov '08  
It helped a lot
I need good css for drop down
Smile

darla

QuestionWould this work...
dswett
13:46 11 Mar '08  
What if you didn't start typing in the first word, would it still show it?

IE:
I start typing in "pie"
I want "apple pie" to show up as a suggestion

Thanks!
AnswerRe: Would this work...
gamerdrew
10:08 5 Aug '08  
For this to work, in LoadCities in the SQL statement change
" WHERE (tblCity.Name LIKE '" + sKeyword.Replace("'", "''") + "%') " +
to
" WHERE (tblCity.Name LIKE '" + "%"+sKeyword.Replace("'", "''") + "%') " +

This will make it work like Firefox 3.0 autocomplete.
QuestionDynamically adding Autosuggest Text Box problem!
giger
2:24 20 Nov '07  
I have a problem adding this control dynamically to my page

AutoSuggestBox txt = new AutoSuggestBox();
txt.MaxLength = 5;
txt.ResourcesDir="/FolderName/asb_includes";
txt.DataType="some_data_type";
txt.Width= new Unit(72,UnitType.Pixel);
txt.Attributes.Add("runat", "server");
txt.ID = someID;
rw.Cells[1].Controls.Add(txt);


It renders ok, but when I try to type in something I get this box pops up 4-5 times:
---------------------
A Runtime error has occured.
Do you wish to Debug?

Line: 2
Error: 'undefined' is null or not an object
---------------------

I have no idea why this happens. Is it possible to add this control the way I'm doing?
GeneralParser error
jebin k
20:51 24 Sep '07  
When i build this application in Visual Studio 2005 i get this error Could not load type 'ASB.GetAutoSuggestData'. E:\Suggest\asb_includes\GetAutoSuggestData.aspx
Please help me out, Thanks in Advance.


Jebin

JEbin
GeneralRe: Parser error
diadem_2k
12:53 25 Sep '07  
even i am getting the same error:
Could not load type 'ASB.GetAutoSuggestData'. asb-includes\GetAutoSuggestData.aspx 1

GeneralRe: Parser error
diadem_2k
13:03 25 Sep '07  
my mistake...i should use codefile property...its fixed by changing the property name to codefile
Questionpopup menu
Adawi
21:30 9 Sep '07  
Wink Hi Mr.
I have a proplem when I use the popup menu with firefox explorer.
its never apper on the page.
I wish to help me.


Adawi
GeneralJavascript is Not Firing
sunny10capri
13:49 22 Jun '07  
Hello,


When i type in the TextBox, an error occured ("Error on Page"). The Javascrip is not fired. I have created a Virtual directory for the project and have given the path for the "ResourcesDir" attribute for textbox control as this C:\Inetpub\wwwroot\GoogleSuggest\asb_includes

I am unable to find the error. I tried debugging the application also. But it seems that javascript is not firing.

Please reply as soon as possible.

Thanks in advance.

Questionworks fine on localhost but a problem on web server
gs_dhaliwal
1:32 22 Jan '07  
Its a great article.....
I have used it..... it works great on my localhost. but gives me problem when i uploaded it to my webserver. it was giving an error in the part
of the dll file.

since i have to register the dll in my VS. is there anything more that i need to do in order to make in working on the web server other than loading all my files including the 4 files i downloaded.

Some body suggested me to create a virtual directory in order make it working. I made a virtual directory. with this there is no error but the fu nctionality of the autosuggest in not working and it is giving me a javascript error. object not specified.

plz reply soon...... Its very urgent

Dhaliwal

QuestionJavascript Error - Object Expected [modified]
Parakkat
22:53 14 Nov '06  
Hi,

I am using Asp.net 2.0. I have tried to implement the AutoSuggest TextBox, but when I enter a character in the textbox, it throws a javascript error "Object Expected". What could be the problem?

Regards,
Maya



-- modified at 5:03 Wednesday 15th November, 2006
AnswerRe: Javascript Error - Object Expected
gabbu1030
1:51 18 May '07  
I am also facing this problem.......
i think it has to do something with Response.Redirect and Server.transfer in ASP.net 2.0
The moment i use Server.transfer for site navigation the control starts throwing this error.D'Oh!
GeneralAdded THe suggest box to my site but using atlas
vik20
18:25 1 Oct '06  
hmmmm. I have also aded this feature to my site but have used Atlas Auto suggest box instead
http://www.vikramlakhotia.com/Post.aspx?postID=46

Vikram
http://www.vikramlakhotia.com/HomePage.aspx
GeneralPressing Space to bring all 10 suggestions
H.Riazi
0:59 15 Sep '06  
Hi;

Is there a way that I could press the space bar and hav all the 10 suggestions?
Please reply A.S.A.P

Thanks
Hadi
GeneralSource is currenty down...
Kirk Severtson
7:19 27 Aug '06  
Will the source page be going back up some time?

Thanks!
GeneralRe: Source is currenty down...
Niraj Sharma
6:24 28 Aug '06  
Sorry about that...

I recentely moved forwarded http://www.autosuggestbox.com to
http://www.entechsolutions.com/DeveloperCorner/AutoSuggestBox.

Thanks for pointing it out.

Eric
QuestionHTTPS [modified]
Berto Vermeer
0:02 6 Jul '06  
Very nice suggest box,
But be aware if you are using the control in combination with SSL and IE.

the control uses for IE a IFrame with a src=about:blank to display the list. This will causes a IE message to display non secure items popup!

solution 1 :
Change the JS script and remove the Iframe.
problem: If you place a combo or a listbox it will be displayed in front of the div


**************************************************************

function asbShowDiv(sDivID, sDivContent)
{
var divMenu;
divMenu=document.getElementById(sDivID);


var sInnerHtml;

//Dont Use IFrame of the same size as div
if (asbIsIE())
{
sInnerHtml = "
";
sInnerHtml += sDivContent;
sInnerHtml += "
";
}
else
{
sInnerHtml=sDivContent;
}


divMenu.innerHTML = sInnerHtml;


if (asbIsIE())
{
var divContent;
divContent=document.getElementById(sDivID + "_content");


//Remember display type
divContent.className="asbMenu";
divMenu.className="asbMenuBase";

}

divMenu.style.visibility = 'visible';
}


***************************************************************************

solution 2:
use the GetAutoSuggestdata url for the source of the IFrame

function asbShowDiv(sDivID, sDivContent,sUrl)
{
var divMenu;
divMenu=document.getElementById(sDivID);


var sInnerHtml;

//Use IFrame of the same size as div
if (asbIsIE())
{
sInnerHtml = "
";
sInnerHtml += sDivContent;
sInnerHtml += "
<iframe id='" + sDivID + "_iframe' src='" + sUrl + "' frameborder='1' scrolling='no'></iframe>";
}


and change the call to asbShowDiv
asbShowDiv(sDivID, oXmlHttp.responseText,sUrl);

*****************************************************************************************
Berto Vermeer

-- modified at 5:29 Thursday 6th July, 2006
GeneralOpera
tetak@monogram.sk
23:47 4 Jul '06  
Original post does not work in Opera. It has two reasons
1. Browser detection false detects opera as IE
solution:
function IsIE()
{
return ( window.navigator.userAgent.indexOf("MSIE ") > 0 && window.navigator.userAgent.indexOf("Opera") <= 0);
}

2. div attribute "value" is reserved for numbers, so if you plan to use string codes (i.e. "BRU", "VIE") you have to rename it to something else ("xvalue") in both source of component (ASBMenuItem.cs) and javascript (AutoSuggestBox.js).

After these trivial changes it works perfect under IE, FF and Opera.

GeneralConcerning AutoSuggestBox.dll
aspdotnet_2
0:12 3 Jul '06  
Hi everybody,Smile
First of all, I would like to comment the artcle given. Its really a gud article that we can develop "Google Suggest" applications easily.
But I've a doubt regarding the AutoSuggestBox.dll. I wish to know the contents of that .dll file. What I can do, if I want to see all the methods n properties written inside in the sourcecode of "AutoSuggestBox.dll" file. Or If I want to write the code of that .dll as a fresh. what I can do??Confused

If anybody knows please reply me.

Thanks In Advance, Big Grin

GeneralRe: Concerning AutoSuggestBox.dll
tex8596
19:22 22 Nov '06  
I agree...great article, but would be better if all code was disclosed.

The man in black ran across the desert....and the gunslinger followed

GeneralVery Nice - Thanks
Andy Hollis
23:49 8 Jun '06  
Worked a treat. This would have taken me days instead of minutes to implement so I would probably never have had enough time Big Grin
GeneralDisable CSS
darwinc
23:20 7 May '06  
Is there a way to disable css?
GeneralHow to customize it to del.icio.us suggestion box style
qiuyl
21:16 5 Apr '06  
I would like to get a del.icio.us style suggestion control. How it could be done quickly using your control?


Last Updated 1 Dec 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010