Go to DotNetFunda.com
 Online : 706 |  Welcome, Guest!   Login
 
Home > Articles > ASP.NET AJAX > Implementing autocomplete textbox in gridview using Ajax autocomplete extender

Submit Article | Articles Home | Search Articles |

Implementing autocomplete textbox in gridview using Ajax autocomplete extender

red flag  Posted on: 1/11/2009 10:05:43 AM by Amit.jain | Views: 20911 | Category: ASP.NET AJAX | Level: Intermediate


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


 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>


If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Found interesting? Add this to:

| More



Please Sign In to vote for this post.

 
Latest post(s) from Amit.jain

Latest Articles

About amiT jaiN

Experience:4 year(s)
Home page:http://csharpdotnetfreak.blogspot.com/
Member since:Friday, December 26, 2008
Level:Starter
Status: [Member]
Biography:

Submit Article

About Us | The Team | Advertise | Contact Us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 9/3/2010 4:02:04 AM