Monday, 2 November 2009

Ajax autocomplete example

Auto completion of a text box is a great way to either suggest and/or restrict user input. After typing a specified number of characters an asynchronous call is made to the database to search for entries that match the input, and they are then displayed at the client in a selectable list beneath the input box.

The ajax control toolkit gives us a neat way of achieving this. I did however, for some reason (probably user error!) have trouble implementing the example they provide. I eventually got it all working and I thought I'd post it here for my reference.

Here's the web service code. In this case my service was called questionCategoryTags:

Public Class questionCategoryTags
Inherits System.Web.Services.WebService


Public Function GetCompletionList(ByVal prefixText As String, ByVal count As Integer) As String()

Dim stringArray() As String
Dim sds As New SqlDataSource
Dim ds As New DataView

sds.ConnectionString = ConfigurationManager.ConnectionStrings.Item("myConnectionString").ToString
sds.DataSourceMode = SqlDataSourceMode.DataSet

sds.SelectCommand = "SELECT DISTINCT Tag FROM Tags WHERE (Tag like '" & prefixText & "%')"
ds = CType(sds.Select(DataSourceSelectArguments.Empty()), DataView)

Dim stringList As New List(Of String)

For Each thing As DataRowView In ds
stringList.Add(thing.Row.Item("Tag"))
Next

stringArray = stringList.ToArray

Return stringArray


End Function


End Class

And don't forget to have this line at the top of your web service. It won't work without it:
system.web.script.services.scriptservice()

And here's the page source:

<ajaxcontrolkit:autocompleteextender completionsetcount="12" delimitercharacters=", " id="AutoCompleteExtender1" minimumprefixlength="2" runat="server" servicemethod="GetCompletionList" servicepath="questionCategoryTags.asmx" showonlycurrentwordincompletionlistitem="true" targetcontrolid="TextBox1" CompletionInterval="1000">
</ajaxcontrolkit:autocompleteextender>

No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!