Click here to Skip to main content
Click here to Skip to main content

AJAX Auto-Suggest Textbox User Control

By , 12 Jun 2008
 

Introduction

This article explains how to develop an AJAX-enabled textbox, which functions as an auto-suggest textbox, using a callback event handler.

In this article, I create a user control with a textbox. When you type something on the textbox, it will go to the server side (database, etc.) and fetch the results according to your textbox input and show it in a div.

Using the code

In this section, I will explain how to create the auto-suggest textbox.

I first create a user control with a textbox and a div element. In the onkeyup of the textbox, call a JavaScript function. Using the callback event handler, it calls the server-side method to filter the results based on what is typed in the textbox. In the user-control server-side, you have to add your code to get data from a DataSet and convert it to an XML string using the ds.getxml() method. In the client-side the XML string is converted to an HTML table using an XSL transform, and the transformed data is shown in a dynamic div tag.

Here is the ASP.NET code:

<!--<span class="code-comment">.ascx --></span>

<script type="text/javascript" src="Common.js"></script>
    
<table >
    <tr>
        <td>        
            <asp:TextBox ID="txtCust" runat="server" ></asp:TextBox>
            <div id="txtDiv" runat="server">
            </div>
        </td>
    </tr>
    <tr>
        <td>
        <div id="myDiv"></div>
            <asp:HiddenField ID="hdnType" runat="server" />
        </td>
     </tr>
     
</table>

Here is the code-behind:

//.ascx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class CustomTextBox : System.Web.UI.UserControl, ICallbackEventHandler
{
    string callbackResult;
    public void SetClassType(string clstype)
    {
        hdnType.Value = clstype;
    }
   
    protected void Page_Load(object sender, EventArgs e)
    {
        txtCust.Attributes.Add("onkeyup", 
                "ShowMatchings('" + this.ClientID + "');");
        txtCust.Attributes.Add("onblur", "onBlur();"); 
        String cbReference = Page.ClientScript.GetCallbackEventReference(this, 
               "arg", "onCallbackComplete",null,true);
        String callbackScript = "function DoClientCallBack(arg)" + 
               "{ " + cbReference + ";}";        
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
        "CallServer", callbackScript, true);
    }

    #region ICallbackEventHandler Members

    public string GetCallbackResult()
    {
        return callbackResult;
    }

    public void RaiseCallbackEvent(string eventArgument)
    {
        try
        {
            callbackResult = xmlResult(eventArgument);
        }
        catch (Exception e)
        {
            Trace.Write(e.Message);
            throw new Exception("Error checking quantity");
        }
    }
    string xmlResult(string Filter)
    {
        DataSet ds = new DataSet();       
        string[] str = Filter.Split('~');
        return "<?xml version='1.0' standalone='yes'?>" + 
               GetResult(resultDS(str[1]), str[0]) ;

    }
    DataSet resultDS(string clsType)
    {
        if (clsType == "City")
        {
            Cities ct = new Cities();
            return ct.GetData();
        }
        else
        {
            World wl = new World();
            return wl.GetData();
        }
    }
    string GetResult(DataSet ds,string Filter)
    {
        DataView dv = ds.Tables[0].DefaultView;
        dv.RowFilter = "Name like '" + Filter + "%'";
        ds.Tables.Clear();
        ds.Tables.Add(dv.ToTable());
        ds.AcceptChanges();
        return ds.GetXml() +"~_~"+ ds.Tables[0].Rows.Count;
    }
    #endregion
}

Add the user control to your project and add a reference to it to your page.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

subbiahkk
Software Developer (Senior)
India India
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Generalarrow keysmemberalokazia15-Jan-10 11:02 
Hi,
is there a way to make this work with the up and down arrow keys as well as enter or tab to insert ?
 
Thank you.
GeneralNot Work In FirefoxmemberJiten @ SPEC27-Oct-09 23:57 
Dear this is not working in firefox.
GeneralGoodmembersskumar12319-Aug-09 20:50 
It helps me to include multiple column data i.e. Name and Desc. thank you
QuestionAnd what ?memberGennady Oster15-Jun-08 23:49 
Hi !
 
There are a lot of such tools on the internet. Even here on the CP site the simple search
with keyword "autosuggest OR autocomplete" will show you 7 pages of results.
 
So at least you have to show the advantages of your control (if any) or explain why the existing solutions are not good for you.
 
Without this your article simply increases the informational noise.
Sorry.
 
Regards,
Gennady
GeneralProblem memberobinna_eke13-Jun-08 6:20 
It doesn't work

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 13 Jun 2008
Article Copyright 2008 by subbiahkk
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid