Thursday, December 18, 2008

Custom AutoComplete 3: Check if AutoComplete List has result items

This kide of requirement I encountered many times.
When the prefixText the user inputed didn't cause any result items from AutoComplete, we need generate an alert for it. For example, the background of TextBox should become red if empty result occurs. See the below thumbnail.

When I'm during the process of typing "mary", the result of web method will be returned. After I type additional "x", the result is empty as "maryx" is not exist. Then the background becomes red.

We need rebuild the onMethodComplete function to attach a callback function after results are updated so that we can generate the alert meassage. Now we can see the code:

<head runat="server">
            visibility: hidden;
            margin: 0px !important;
            background-color: inherit;
            color: windowtext;
            border: buttonshadow;
            border-width: 1px;
            border-style: solid;
            cursor: 'default';
            overflow: auto;
            height: 200px;
            text-align: left;
            list-style-type: none;
            font-family: courier new;
            font-size: 8pt;
        /* AutoComplete highlighted item */.autocomplete_highlightedListItem
            background-color: #e3ec6e;
            color: black;
            padding: 1px;
        /* AutoComplete item */.autocomplete_listItem
            background-color: window;
            color: windowtext;
            padding: 1px;


<script type="text/javascript">
    function pageLoad() {

        $find('autocomplteextender1')._onMethodComplete = function(result, context) {

            $find('autocomplteextender1')._update(context, result, /* cacheResults */false);
            webservice_callback(result, context);

    function webservice_callback(result, context) {

        if (result == "")
            $find("autocomplteextender1").get_element().style.backgroundColor = "red";
            $find("autocomplteextender1").get_element().style.backgroundColor = "white";


    <form id="form2" runat="server">
    <asp:ScriptManager ID="ScriptManager2" runat="server" />
    <asp:UpdatePanel ID="uppanle1abcxyz" runat="server">
            <asp:TextBox ID="TextBox1" runat="server" Width="150px"></asp:TextBox>
            <cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" BehaviorID="autocomplteextender1"
                MinimumPrefixLength="1" ServicePath="AutoComplete.asmx" ServiceMethod="GetCompletionList1"
                TargetControlID="TextBox1" CompletionListCssClass="autocomplete_completionListElement"
                CompletionListItemCssClass="autocomplete_listItem" CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
                CompletionInterval="500" DelimiterCharacters=";" CompletionSetCount="10" Enabled="true">