<ajaxToolkit:ToolkitScriptManager runat="server" ID="ScriptManager1" />
<asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
<ajaxToolkit:AutoCompleteExtender
runat="server" OnClientPopulated="dd" OnClientItemSelected="itemSelected"
BehaviorID="AutoCompleteEx"
ID="autoComplete1"
TargetControlID="myTextBox"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="2"
CompletionInterval="1000"
EnableCaching="true"
CompletionSetCount="8"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
DelimiterCharacters=";, :">
</ajaxToolkit:AutoCompleteExtender>
</form>
</body>
<script type="text/javascript">
function itemSelected(ev)
{
var index=$find("AutoCompleteEx")._selectIndex;
var dd=$find("AutoCompleteEx").get_completionList().childNodes[index]._value;
$find("AutoCompleteEx").get_element().value=dd;
}
function dd()
{
var comletionList=$find("AutoCompleteEx").get_completionList();
for(i=0;i<comletionList.childNodes.length;i++)
{
var _value=comletionList.childNodes[i]._value;
comletionList.childNodes[i]._value=_value.substring(_value.lastIndexOf('|')+1);// parse id to _value
_value=_value.substring(0,_value.lastIndexOf('|'));
comletionList.childNodes[i].innerHTML=_value.replace('|','<br/>');
}
}
</script>
WebMethod in AutoComplete.asmx:
public string[] GetCompletionList(string prefixText, int count)
{
System.Threading.Thread.Sleep(2000);
if (count == 0)
{
count = 10;
}
if (prefixText.Equals("xyz"))
{
return new string[0];
}
Random random = new Random();
List<string> items = new List<string>(count);
for (int i = 0; i < count; i++)
{
char c1 = (char)random.Next(65, 90);
char c2 = (char)random.Next(97, 122);
char c3 = (char)random.Next(97, 122);
int id = i;
int age = random.Next(18, 70);
items.Add(prefixText + c1 + c2 + c3 +"|"+age.ToString()+"|"+id.ToString());
}
return items.ToArray();
}
ID, Name and Age will be returned from web method to the client. JavaScript will change the format of result and set the value as ID. When you select the item, the value will be as the text of TextBox.
In this way, we can even append an image in font of each item. I will intoduce about "AutoComplete with Image" next time.