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.
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
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;
}
}
|
<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. |
|||
|
|||
27 comments :
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
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
k i m trying
m getting the data from database but still its not working
It working fine for me also with process bar
suresh addition to the above code
can you explain to me how to highlight the typed character in the dropdown list
How to select multiple values ?
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..
sir i join one company now start asp.net developer so if i doubt pls retify me.. thank u for am subscribe ur website..
hi...i tried the code ...web service is working fine...but im not getting output in my application
where is database ??
its not attached
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
I am creating service for auto complete text box then add servicereference to my project then how can set sevicepath of Ajax AutoCompleteExtender
no it's not good
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
Dear suresh,
how to create autocomplete textbox which can search multipleitem from database
how to debug the code and test whether your getting data from database or not
how to debug the code and test whether your getting data from database or not
Hey suresh,
i m trying dis code ..but it ll not working...give me a solution
for (int i = 0; i < dt.Rows.Count; i++)
{
CountryNames.Add(dt.Rows[i][0].ToString());
}
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
hello sir ,
its showing error webservice.asmx not found
what should do..
if you select 1 column then edit as:
CountryNames.Add(dt.Rows[i][0].ToString());
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
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);
}
Note: Only a member of this blog may post a comment.