Archive for November, 2012

Using the AutoCompleteExtender control

I came across a business requirement to have suggested values popup in a TextBox while the user was typing, and those values must be members of the Jackson 5. Since this requirement is surely one almost every developer faces at one time in their career, here is how to duplicate it.  

In the aspx page, register the AjaxControlToolkit control:  

     <%@ Register TagPrefix=”uc1″ Namespace=”AjaxControlToolkit” Assembly=”AjaxControlToolkit”%>  

You do have the AjaxControlToolkit DLL, right? If not, go to http://ajaxcontroltoolkit.codeplex.com/ and go get it.  

And of course, you’ll need a TextBox to attach the extender to, the ScriptManager control for that Ajax stuff, and the extender control itself:    

    <asp:TextBox ID=”txtSinger” MaxLength=”50″ runat=”server” />
    <asp:ScriptManager ID=”scriptMan” runat=”server” />

    <uc1:AutoCompleteExtender ID=”autoExtender” CompletionInterval=”1000″ EnableCaching=”true” MinimumPrefixLength=”2″ ServiceMethod=”GetJacksons” TargetControlID=”txtSinger ” runat=”server” />

What I’ve done via the MinimumPrefixLength property is say only hit the web service until I’ve entered two characters. To see the full list of properties, go to http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AutoComplete/AutoComplete.aspx. It’s a marvelous read, full of intrigue and betrayal.  

And now for the code-behind magic:  

     [WebMethod] public static string[] GetJacksons(string prefixText, int count) 
    {
        string[] arr1 = new string[] { “Jackie”, “Jermaine”, “Tito”, “Marlin”, “Michael” };
        return arr1.Where(i => i.IndexOf(prefixText) > -1).ToArray(); 
    } 

Now, when you enter a few characters into the txtSinger TextBox, you will get a list back of matching values. If you want to see what it looks like to get multiple matching values, add the strings “Jackeroo” and “Jackabooboo” to the list and rerun it, typing “Ja” in the TextBox. I would add them myself, but that would break the continuity of the Jackson 5 and cause my tutorial to become a laughingstock, not the technical masterpiece that it is now.

Leave a comment