Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Ajax autocompleteextender example with progressbar image in asp.net

Mar 6, 2011
Introduction:

Here I will explain how to use Ajax AutoCompleteExtender to display the words begin with prefix typed into the textbox using asp.net

Description:

In Google if we type anything in search textbox we will find all related words below the textbox it has developed by using Ajax autocomplete extender. We can attach Ajax autocomplete exteneder to any textbox to implement this and after assign autocomplete extender to textbox and
type more content than the specified minimum word length, a popup will show words or phrases starting with that value.  So the user can choose exact word from the popup panel. Here we are implementing autoCompleteextender to fetch data from the database through a Webservice.

First design table in your database like this 


Column Name
Data Type
Allow Nulls
ID
Int(set identity property=true)
No
CountryName
Varchar(50)
Yes
After that add AjaxControlToolkit to your bin folder and design your aspx page like this

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Ajax AutoCompleteExtender Sample</title>
<script type="text/javascript">
function ShowProcessImage() {
var autocomplete = document.getElementById('txtCountry');
autocomplete.style.backgroundImage = 'url(loading1.gif)';
autocomplete.style.backgroundRepeat = 'no-repeat';
autocomplete.style.backgroundPosition = 'right';
}
function HideProcessImage() {
var autocomplete = document.getElementById('txtCountry');
autocomplete.style.backgroundImage  ='none';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
<ajax:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtCountry" ServicePath="WebService.asmx"
MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1" CompletionInterval="1000" ServiceMethod="GetCountries" OnClientPopulating="ShowProcessImage" OnClientPopulated="HideProcessImage" >
</ajax:AutoCompleteExtender>
</div>
</form>
</body>
</html>
Here if you observe above code for autocompleteextender I have declared different properties I will explain each property clearly

TargetControlID - The TextBox control where the user types content to be automatically completed.

ServiceMethod - The web service method to be called to fetch the records from database. The signature of this method must match the following: 
[System.Web.Script.Services.ScriptService]
public List<string> GetCountries(string prefixText)
Or

[System.Web.Script.Services.ScriptService]
public List<string> GetCountries(string prefixText, int count)
We can replace " GetCountries " with a name of your choice, but the return type and parameter name and type must exactly match, including case.

ServicePath - The path to the web service that the extender will pull the word\sentence completions from.

EnableCaching- Caching is turned on, so typing the same prefix multiple times results in only one call to the web service.

MinimumPrefixLength- Minimum number of characters that must be entered before getting suggestions from the web service.

CompletionInterval - Time in milliseconds when the timer will kick in to get suggestions using the web service.

CompletionSetCount - Number of suggestions to be retrieved from the web service.

OnClientPopulating - This one used to display progress image in textbox during getting the data from database using web service.

OnClientPopulated - This one used to hide progress image in textbox after finishing data retrieval from database.

Don’t get confuse I explained all the properties details only it’s very simple to implement auto completion textbox after completion of your aspx page design add one new webservice page to your application and add following namcespaces in your webservice code behind page


using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
After completion of writing namespaces and write the following code in webservice page


/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public List<string> GetCountries(string prefixText)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("select * from Country where CountryName like @Name+'%'",con);
cmd.Parameters.AddWithValue("@Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable  dt = new DataTable( );
da.Fill(dt);
List<string> CountryNames = new List<string>();
for(int i=0;i<dt.Rows.Count;i++)
{
CountryNames.Add(dt.Rows[i][1].ToString());
}
return CountryNames;
}
}
After that set your database connection in web.config like this

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >
Demo


Download sample code attached

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

27 comments :

Unknown said...

Dear Suresh



using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

///
/// Summary description for WebService
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{

public WebService()
{

//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public List GetCountries(string prefixText)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("select * from country where countryname like @Name+'%'", con);
cmd.Parameters.AddWithValue("@Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List CountryNames = new List();
for (int i = 0; i < dt.Rows.Count; i++)
{
CountryNames.Add(dt.Rows[i][1].ToString());
}
return CountryNames;
}
}



The Program run without error but after the type the initial char of country nothing hapen. plz solve this.

Thank You

Suresh Dasari said...

hi subhash,
i tested code it's working fine you should try to debug the code and test whether your getting data from database or not

Unknown said...

k i m trying

Anonymous said...

m getting the data from database but still its not working

Anonymous said...

It working fine for me also with process bar

Anonymous said...

suresh addition to the above code
can you explain to me how to highlight the typed character in the dropdown list

Anonymous said...

How to select multiple values ?

vignesh said...

Using Webusercontrol create five are six text boxes and Retrive these in to two aspx pages

ie means aspx first three text box display in first aspx after remaining ll display on second aspx using webuser control..

vignesh said...

sir i join one company now start asp.net developer so if i doubt pls retify me.. thank u for am subscribe ur website..

Anonymous said...

hi...i tried the code ...web service is working fine...but im not getting output in my application

Aryan Patel said...

where is database ??
its not attached

R.s.v.v. Prasad Rao said...
This comment has been removed by the author.
R.s.v.v. Prasad Rao said...

Sorry iam not getting any output and in case even i get output only some times and only for 1 value i have done all the modifications please help me out

Ranjan said...

I am creating service for auto complete text box then add servicereference to my project then how can set sevicepath of Ajax AutoCompleteExtender

Unknown said...

no it's not good

rohit said...

its awesome but i have a project in which i need to add dictionary words in my sql database can you tell me the all procedure how can i add oxford dictionary database in my project

Unknown said...

Dear suresh,
how to create autocomplete textbox which can search multipleitem from database

Divya said...

how to debug the code and test whether your getting data from database or not

Unknown said...

how to debug the code and test whether your getting data from database or not

Unknown said...

Hey suresh,

i m trying dis code ..but it ll not working...give me a solution

Rajkumar Palnati said...

for (int i = 0; i < dt.Rows.Count; i++)
{
CountryNames.Add(dt.Rows[i][0].ToString());
}

wasim said...

Hello , if i am suggested list... select from keybord up,down arrow then selected id not set to hidden field..in javascript ... i dont want any post back..let me please any suggestion

anand said...
This comment has been removed by the author.
anand said...

hello sir ,
its showing error webservice.asmx not found
what should do..

Anonymous said...

if you select 1 column then edit as:
CountryNames.Add(dt.Rows[i][0].ToString());

Anonymous said...

someone tell me i am accessing this services on simple .aspx then i am getting the result when i am accessing on child page means using Master page then web service method is not accessing .

Thanx
Waiting for reply

Unknown said...

Hello Sir,
I have tried this but I don't get the output



public List GetNames(string Prefixtext)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcon"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("select itemdescription from itemmaster where itemdescription like '%'+@Name+'%'", con);
cmd.Parameters.AddWithValue("@Name", Prefixtext);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List ItemNames = new List();
for (int i = 0; i < dt.Rows.Count; i++)
{
ItemNames.Add(dt.Rows[i][0].ToString());
}
return ItemNames;
}
The above code is my webservice.cs file
Now I want to add this webservice as a reference
Can u plz suggest me how to use this webservice for a textbox in a default.aspx page using ajax autocompleteextender


function chkgroupcode() {
var grpcode = document.getelementbyid("textbox1");
if (grpcode.value != '') {
webservice.getnames(grpcode.value, onresult, onerror, ontimeout);
}

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.