AutoComplete functionality to textbox using AJAX autocomplete extender


/ Published in: Visual Basic
Save to your folder(s)

In this example i am implementing the AutoComplete functionality to textbox using AJAX autocomplete extender, for this we need to create a web service which calls the method to fetch data from database and display results as suggestions for textbox


Copy this code and paste it in your HTML
  1. Imports System.Collections.Generic
  2. Imports System.Web.Services
  3. Imports System.Data.SqlClient
  4. Imports System.Configuration
  5. Imports System.Data
  6. <WebService> _
  7. <WebServiceBinding(ConformsTo := WsiProfiles.BasicProfile1_1)> _
  8. <System.Web.Script.Services.ScriptService> _
  9. Public Class AutoComplete
  10. Inherits WebService
  11. Public Sub New()
  12. End Sub
  13. <WebMethod> _
  14. Public Function GetCompletionList(prefixText As String, count As Integer) As String()
  15. If count = 0 Then
  16. count = 10
  17. End If
  18. Dim dt As DataTable = GetRecords(prefixText)
  19. Dim items As New List(Of String)(count)
  20. For i As Integer = 0 To dt.Rows.Count - 1
  21. Dim strName As String = dt.Rows(i)(0).ToString()
  22. items.Add(strName)
  23. Next
  24. Return items.ToArray()
  25. End Function
  26.  
  27. Public Function GetRecords(strName As String) As DataTable
  28. Dim strConn As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString
  29. Dim con As New SqlConnection(strConn)
  30. Dim cmd As New SqlCommand()
  31. cmd.Connection = con
  32. cmd.CommandType = System.Data.CommandType.Text
  33. cmd.Parameters.AddWithValue("@Name", strName)
  34. cmd.CommandText = "Select Name from Test where Name like '%'+@Name+'%'"
  35. Dim objDs As New DataSet()
  36. Dim dAdapter As New SqlDataAdapter()
  37. dAdapter.SelectCommand = cmd
  38. con.Open()
  39. dAdapter.Fill(objDs)
  40. con.Close()
  41. Return objDs.Tables(0)
  42. End Function
  43. End Class
  44.  
  45. '------------------------------------------------------------------------------
  46. 'If u want to use Sessions, u have to change <WebService> _ for
  47. '<WebMethod(EnableSession:=True)> _
  48. '------------------------------------------------------------------------------
  49. '--------------------------ASP.NET CODE ----------------------------------------------------
  50.  
  51. <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Name") %>' ></asp:TextBox>
  52. <ajaxToolkit:AutoCompleteExtender runat="server" ID="autoComplete1" TargetControlID="txtName" ServicePath="AutoComplete.asmx" ServiceMethod="GetCompletionList" MinimumPrefixLength="1" CompletionInterval="10" EnableCaching="true" CompletionSetCount="12" />

URL: http://www.dotnetfunda.com/articles/article224.aspx

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.