Friday, October 30, 2009

How to set up the autocompleteextender

The auto extender function is very handy. It is Google like in that it will display available matches in a text box drop-down. In order to makes this AJAX object the best that it can be it is necessary to be able to retrieve the ID of the selected item. Below are the steps to accomplish this.



1. Place an autoextender tag in your html and link it to your text box.


    For instance:

          <asp:TextBox ID="txtSearch" runat="server" CssClass="textbox" width="160px"></asp:TextBox>


          <cc1:AutoCompleteExtender ID="aceSearch" runat="server" TargetControlID="txtSearch" FirstRowSelected="true" ServiceMethod="GetPackages" ServicePath="packagemanager.asmx" MinimumPrefixLength="1" CompletionInterval="500" CompletionListCssClass="AutoCompleteFlyout" CompletionListItemCssClass="AutoCompleteFlyoutItem" CompletionListHighlightedItemCssClass="AutoCompleteFlyoutHilightedItem" OnClientItemSelected="GetPackageID" />


2. Next, create a web service file and place in it a function similar to the one below.


 <WebMethod()> _
Public Function GetPackages(ByVal prefixText As String) As String()

'Create a list to hold the package ID and name
Dim Packages As New List(Of String)()

'Set up the SQL connection using the connection string from above
Dim sqlConn As New SqlConnection(conWork2GoalString)

'Open the connection
sqlConn.Open()

'Create the SQL command
Dim sqlSelect As New SqlCommand("SELECT packagemasterID, package_name FROM adpack_packagemaster WHERE package_name LIKE @prefixText AND package_end_date >= CAST(FLOOR(CAST( GETDATE() AS FLOAT)) AS DATETIME)", sqlConn)

'Set up the SQL data adapter using the SQL command from above
Dim sqlAdapter As New SqlDataAdapter(sqlSelect)

'Add the parameter
sqlAdapter.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = "%" & prefixText & "%"

'Set up the datareader
Dim drPackage As SqlDataReader

'Execute the datareader
drPackage = sqlSelect.ExecuteReader

'Loop through the datareader
While drPackage.Read()

          'Grab the package name and ID
          Dim package As String = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(drPackage("package_name").ToString(), drPackage("packagemasterID").ToString())

          'Add the package to the list
          Packages.Add(package)

End While

'Close the datareader
drPackage.Close()

'Close the connection
sqlConn.Close()

'Dispose of the connection
sqlConn.Dispose()

'Return the packages list/array
Return Packages.ToArray()

End Function