/ Published in: Visual Basic
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
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
Imports System.Collections.Generic Imports System.Web.Services Imports System.Data.SqlClient Imports System.Configuration Imports System.Data <WebService> _ <WebServiceBinding(ConformsTo := WsiProfiles.BasicProfile1_1)> _ <System.Web.Script.Services.ScriptService> _ Public Class AutoComplete Inherits WebService Public Sub New() End Sub <WebMethod> _ Public Function GetCompletionList(prefixText As String, count As Integer) As String() If count = 0 Then count = 10 End If Dim dt As DataTable = GetRecords(prefixText) Dim items As New List(Of String)(count) For i As Integer = 0 To dt.Rows.Count - 1 Dim strName As String = dt.Rows(i)(0).ToString() items.Add(strName) Next Return items.ToArray() End Function Public Function GetRecords(strName As String) As DataTable Dim strConn As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString Dim con As New SqlConnection(strConn) Dim cmd As New SqlCommand() cmd.Connection = con cmd.CommandType = System.Data.CommandType.Text cmd.Parameters.AddWithValue("@Name", strName) cmd.CommandText = "Select Name from Test where Name like '%'+@Name+'%'" Dim objDs As New DataSet() Dim dAdapter As New SqlDataAdapter() dAdapter.SelectCommand = cmd con.Open() dAdapter.Fill(objDs) con.Close() Return objDs.Tables(0) End Function End Class '------------------------------------------------------------------------------ 'If u want to use Sessions, u have to change <WebService> _ for '<WebMethod(EnableSession:=True)> _ '------------------------------------------------------------------------------ '--------------------------ASP.NET CODE ---------------------------------------------------- <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Name") %>' ></asp:TextBox> <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