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

  • Nominate yourself for "Agile Software Development using Scrum" online session for FREE, click here.

  • Download OOPS and ASP.NET Online training session video and PPT from here.

Submit Article | Articles Home | Search Articles |

Implementing autocomplete textbox in gridview using Ajax autocomplete extender

 Download source file
 Posted on: 1/11/2009 10:05:43 AM by Amit.jain | Views: 16242 | Category: ASP.NET AJAX | Level: Intermediate | Print Article
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

Buy online comprehensive training video pack just for $35.00 only, see what's inside it.

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.

Interesting?   Share and Bookmark this kick it on DotNetKicks.com


About amiT jaiN

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

   ◘ Disabling copy paste in a textbox on aspx page posted on 1/22/2009 8:21:06 AM
   ◘ Creating AutoComplete TextBox in Windows Froms using C# posted on 1/13/2009 6:45:30 AM
   ◘ Implementing autocomplete textbox in gridview using Ajax autocomplete extender posted on 1/11/2009 10:05:43 AM
   ◘ Implementing search in GridView and highlight results posted on 1/8/2009 5:22:39 AM
   ◘ Redirection to Login page after session time out posted on 1/5/2009 7:49:14 AM


Submit Article

About Us | The Team | Advertise | Contact Us | Feedback | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found copied contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
All rights reserved to DotNetFunda.Com. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
(Best viewed in IE 6.0+ or Firefox 2.0+ at 1024 * 768 or higher)