Simple AutoSuggest Textbox using JQuery

Few months back, one of my colleague from UI team, introduced JQuery to me, our purpose was to show some nice dialog boxes using JQuery. After some time I moved in to some Windows projects. And now I am back in web development, few days back I got a task to implement a Auto suggest textbox for US Cities. Initialy I was planning to implement it via ASP.Net AJAX, then I thought about simple
implementations. After some googling I found one solution, I modified the code slightly, and implemented it in a Custom user control.

Here is the C# custom control (AutoSuggestTextBox) code.


[DefaultProperty("Text")]
[ToolboxData("<{0}:AutoSuggestTextBox runat=server></{0}:AutoSuggestTextBox>")]
public class AutoSuggestTextBox : WebControl
{
protected override void RenderContents(HtmlTextWriter output)
output.WriteLine("<script type=\"text/javascript\">");
output.WriteLine("$().ready(function() {");
output.WriteLine(string.Format("$(\"#{0}TextControl\").autocomplete(\"{0}.ashx\");", this.ID));
output.WriteLine("});</script>");
output.WriteLine(string.Format("<input type=\"text\" id=\"{0}TextControl\" name=\"{0}TextControl\" />", this.ID));
}
}

In the implementation, I need to give the output from the database as string, so I implemented the code in a asp.net handler(ASHX) file. And in the ProcessRequest method, I wrote the following code.

if (!string.IsNullOrEmpty(context.Request.QueryString["q"])) // remember, 'q' is the query the autosuggest will pass
        {
            SqlDataReader reader;
            string query = string.Format("SELECT [CityName] FROM [City] WHERE [CityName] LIKE '%{0}'", context.Request.QueryString["q"].ToString());
            using (SqlConnection connection = new SqlConnection("Server=mydbserver; User Id=sa;Password=mypassword;Database=mylookups;"))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    reader = command.ExecuteReader(CommandBehavior.CloseConnection);
                    while (reader.Read())
                    {
                        context.Response.Write(reader["CityName"].ToString() + Environment.NewLine);
                    }
                    reader.Close();
                }
                connection.Close();
            }
        }

Note: I am not promising the above code is optimised. [:)]

And the ASPX Page you need to add reference to following JS Files and Style.

    <script type="text/javascript" language="javascript" src="jquery.js"></script>
    <script src="jquery.autocomplete.js" type="text/javascript"></script>
    <style type="text/css">
        .ac_odd {background:#dddddd;}
        .ac_results { padding: 0px; border: 1px solid black; background-color: white; overflow: hidden; z-index: 99999; }
        .ac_results ul { width: 100%; list-style-position: outside; list-style: none; padding: 0; margin: 0; }
        .ac_results li { margin: 0px; padding: 2px 5px; cursor: default; display: block; font: menu; font-size:12px; line-height: 16px; overflow: hidden; }
        .ac_loading { background:url(loading.jpg) right no-repeat; }
        .ac_over { background-color: #0A246A; color: white; }
    </style>

We have completed almost everything, then compile the project, drag the Custom control from toolbox to ASPX page, where you refering the JS Files and CSS. The ASHX File name should be the name of the control. Like if the control’s name is AutoSuggestCity, the ASHX Filename should be AutoSuggestCity.ashx. Please modify the control code if you want to change it.

After running you will get a Textbox, type something there, you will get the suggestions. Here is the one I got.

autosuggest

You can download JQuery from JQuery website. – www.jquery.com. And autosuggest plugin from AutoSuggest plugin page.

  • http://www.winsoftwares.net Sonia

    The code is nice but i need a real time demo with atleast 5 different example. sothat i can choose one the best suitable for me. thanks

  • please send me autoSuggess TextBox using Jquery

    Please send me Simple AutoSuggest Textbox using JQuery to romanox_x@yahoo.com.Thanks

  • http://google.com Ranbir

    Sonia, send an email to me.. so that i can send 5 different examples and u can choose one the best suitable for you.

  • rajesh

    Ranbir,

    Please send me the demo code in .net for autosuggestbox. My email id is rajeshvuta
    at yahoo

  • Vinay

    i see the code, its good but please tell me where is the ASHX file?
    Actually send me some brief details to implement the code. Please

  • http://anuraj.wordpress.com/ anuraj

    The second code block, which tells about the DB Connection string and other C# code, is the content of the ASHX file. And I am calling it in the Custom control code.

    thanks for the comments :)

  • http://bulenok.com/ f0rza

    Thanks for excellent code sample!

  • Charu

    This is good example… but i need code how can i run this in my application. Because I have already implemented this code our application using XML. but when we run the application in the two browser at the same time then it returns as error.

    name.xml is used by some another process.

    this create a problem for me.

    overall it is ok.

    • http://www.dotnetthoughts.net/ Anuraj P

      Thanks :), it may be because you locked the file by ASP.Net. Please make sure you are closing the file. It may help you.

  • charu

    @Anuraj P

    Thanks for the reply.
    But when we open two browsers at the same time. then we have no option to check the file either it is saved at not, Because at both time, it reads the file & the filled all selected data into the autosuggested Textbox.

  • Perry

    Can someone redirect me to a page where I can find the project file or .js files?

  • murty

    This is exactly what i am looking for. Very nice article.
    Can you please send me code in VB.net

    thank you
    Sri

  • http://www.google.com sergio

    please send me ur Simple AutoSuggest Textbox using JQuery
    my mail id is sergioramosiker@gmail.com

  • http://anuraj.wordpress.com/ anuraj

    Thank you Forza [:)]