Search
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Articles Author
Fri, 24-Oct-2014 Authors
All Time Authors
Sourav.Kayal
39750
Sheonarayan
38050
Niladri.Biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads
 Article

Implementing autocomplete textbox in gridview using Ajax autocomplete extender

Amit.jain
Posted by under ASP.NET AJAX category on for Intermediate level | Views : 67140 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
In this example i am implementing the AutoComplete functionality to textbox in the EditItemTemaplate of GridView 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

 Download source code for Implementing autocomplete textbox in gridview using Ajax autocomplete extender


Creating a web service
For this add a new webservice to the project by right clicking on root of application in solution explorer and select add new Item than web service,name it AutoComplete.asmx or whatever you want, in the code behind of the web service we write methods to get the records from database and a web method called GetCompletionList which takes text entered in textbox as parameter to search database , this method gets automatically called when ever user types anything in the textbox, the code for this web service is like this


Code behind for AutoComplete.asmx
In the code behind i've written a method called GetRecords which takes string as parameter to fetch records from databse and a webmethod called GetCompletionList which also takes string prefixText and int count as input parameters, GetCompletionList method gets called whenever user enters somthing in TextBox
using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
[WebService]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : WebService
{
    public AutoComplete()
    {
    }
    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {
        if (count == 0)
        {
            count = 10;
        }
        DataTable dt = GetRecords(prefixText);
        List<string> items = new List<string>(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["DatabaseConnectionString"].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 Name from Test where Name like '%'+@Name+'%'";
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        con.Open();
        dAdapter.Fill(objDs);
        con.Close();
        return objDs.Tables[0];
    }
}
Html source of aspx page
In the html source for aspx page add a script manager and within scriptmanager tag , add ServiceReference and path to asmx file, in gridview add autocomplete extender for the textbox which we want to autocomplete like this
<asp:ScriptManager ID="ScriptManager1"
runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
</Services>
</asp:ScriptManager>
and the settings for autocomplete extender
<ajaxToolkit:AutoCompleteExtender
      runat="server"
             ID="autoComplete1"
            TargetControlID="txtName"
             ServicePath="AutoComplete.asmx"
             ServiceMethod="GetCompletionList"
             MinimumPrefixLength="1"
             CompletionInterval="10"
             EnableCaching="true"
             CompletionSetCount="12" />
Complete soource of the page
 <body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
</Services>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Eval("ID") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Bind("ID") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
<asp:Label ID = "lblName" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<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" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location" SortExpression="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#Eval("Location") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#Bind("Location") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Test]" UpdateCommand="Update Test set [Name] = @Name where ID = @ID">
<UpdateParameters>
<asp:Parameter Name="Name" />
<asp:Parameter Name="ID" />
</UpdateParameters>
</asp:SqlDataSource>
</div>
</form>
</body>

Page copy protected against web site content infringement by Copyscape
About the Author

Amit.jain

Full Name: amiT jaiN
Member Level: Starter
Member Status: Member
Member Since: 12/26/2008 7:19:35 AM
Country:

http://csharpdotnetfreak.blogspot.com/

Login to vote for this post.
Found interesting? Add this to:


Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)