Ajax AutoCompleteExtender In Master Page Asp.Net

This Example shows How To Use Ajax AutoCompleteExtender TextBox In Master Page In Asp.Net.

Open Visual Studio and create new website, add master page in it and design it as you want.

Create a BIN folder in application and add AjaxControlToolkit.dll in it.

I have use Northwind database to fetch names for AutoCompletion list.

Add Connection String in web.config file

<connectionStrings>
<add name="NorthwindConnectionString" 
     connectionString="Data Source=AMITJAIN\SQL;
                       Initial Catalog=Northwind;
                       User ID=amit;Password=password"
providerName="System.Data.SqlClient"/>
</connectionStrings>


Place ToolkitScriptManager on Master Page inside form tag, one textbox and Add Ajax AutoComplete Extender from Toolbox.

HTML SOURCE OF MASTER PAGE
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"/>
 
<asp:TextBox ID="txtAutoComplete" runat="server"/>
                               
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" 
                          runat="server" 
                          DelimiterCharacters="" 
                          Enabled="True" 
                          ServicePath="~/AutoComplete.asmx" 
                          ServiceMethod="GetCompletionList"
                          TargetControlID="txtAutoComplete"
                          MinimumPrefixLength="1" 
                          CompletionInterval="10" 
                          EnableCaching="true"
                          CompletionSetCount="12">
</asp:AutoCompleteExtender>
                
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
 
</form>
</body>
</html>


We can set CompletionList WIdth and styles using CSS or use AutoCompleteExtender In GridView or Windows Forms Application.

Add new webservice, name it AutoComplete.asmx and write following code in it's code behind.

C#
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService {

    public AutoComplete () 
    {
    }

    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {
        if (count == 0)
        {
            count = 10;
        }
        DataTable dt = GetRecords(prefixText);
        List items = new List(count);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string strName = dt.Rows[i][0].ToString();
            items.Add(strName);
        }
        return items.ToArray();
    }

    public DataTable GetRecords(string strName)
    {
        string strConn = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Parameters.AddWithValue("@Name", strName);
        cmd.CommandText = "Select FirstName from Employees where FirstName like '%'+@Name+'%'";
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        con.Open();
        dAdapter.Fill(objDs);
        con.Close();
        return objDs.Tables[0];
    }
}

VB.NET
Imports System.Collections.Generic
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Data
Imports System.Configuration

 _
 _
 _
Public Class AutoComplete
 Inherits System.Web.Services.WebService

 Public Sub New()
 End Sub

  _
 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("NorthwindConnectionString").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 FirstName from Employees where FirstName 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


Build and run the application.

If you like this post than join us or share

4 comments:

rakesh said...

good ...


Unknown said...

it's not working for me. could you give me hand please?
form_dosen.aspx



















-------------------------------------------------------------------------------------------------------------
WebServices.asmx.vb
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Data.SqlClient

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
_
_
_
_
Public Class WebService1
Inherits System.Web.Services.WebService
_
Public Function cariDosen(ByVal nama As String) As String()
bacaData_tabel = dataDosen(nama)
Dim items As New List(Of String)()
Dim lengkap As String
For x As Integer = 0 To bacaData_tabel.Rows.Count - 1
lengkap = bacaData_tabel.Rows(x)(0).ToString()
items.Add(lengkap)
Next x
Return items.ToArray()
End Function

Public Function dataDosen(ByVal nama_dosen As String) As DataTable
Using perintah_Query As New SqlCommand()
perintah_Query.CommandType = CommandType.StoredProcedure
perintah_Query.CommandText = "sp_tampil_nama_dosen"
perintah_Query.Parameters.AddWithValue("@p1", nama_dosen)
perintah_Query.Connection = koneksi_db
bacaData_adapter = New SqlDataAdapter(perintah_Query)
bacaData_set = New DataSet()
bacaData_adapter.Fill(bacaData_set)
Return bacaData_set.Tables(0)
End Using
End Function
End Class


Anonymous said...

thanks for your attention about this topic


Djama said...

not working with me, asp.net 4.5


Find More Articles