AspdotnetCodes.com
Search
Articles
Books
Resources
Asp.Net News
Downloads
Free Tech Magazines
Asp.Net Web Hosting
Archives
Softwares
Newsletter
Suggest Us
Link to Us
Feeds Subscription
Articles
Questions & Answers
Tips & Tricks
 AutoComplete Textbox with Additional Parameters From Database
Posted by Moderator1 on 7/23/2007 11:16:01 PM Category: AJAX
Total Views : 159293
Add to my favorites
Email to friend
  
Introduction
This article explains the concept of the Ajax AutoComplete Textbox to fetch data from the database with additional parameter.
A Textbox can be integrated with the Ajax AutoComplete Extender to perform AutoComplete functionality and it also helps to fetch data from the database. This concept is explained clearly in our previous article titled “AutoComplete From Database". This article is aimed to provide more knowledge about the AutoComplete Extender which can take some additional parameters through which we can fine tune a data fetched from the database. To achieve this we need to install the new AjaxControlToolkit version 10618, released on June 2007.

Key Properties

The main properties to achieve this AutoComplete Textbox with additional parameter are contextKey and UseContextKey. These two properties help to set some additional parameters to the prefixText that is passed to the webservice. ContextKey ia a user or page specific context provided to an optional overload of the web method described in the ServiceMethod of the AutoComplete Extender. If the context key is used, it should have the same signature with an additional parameter named contextKey of type string. The UseContextKey is to specify whether or not the contextKey property should be used.

Sample Scenario

We are going to fill a single AutoComplete Textbox with two different types of values based on the condition provided from a DropDownList control. The first type of value will be country name and the second type of value will be the states in US. You can choose the type of values to be filled in the AutoComplete Textbox from the DropDownList provided. This sample is for only demonstration purpose, but in real time you can process any type of contextKey values to achieve excellent stuffs.

Make sure you have installed latest version (10618) of AjaxToolkit control in your development system. In your Ajax Enabled website, drag and drop a Textbox from your Toolbox. Then drag and drop a ScriptManager and AutoCompleteExtender to your Default.aspx page. Then add a webservice to your project as WebService.asmx. Add the ScriptService reference to the webserive as follows.
[System.Web.Script.Services.ScriptService]
Now, write a webmethod ‘GetCountryOrStatesInfo’ to fetch the data from the Country or StatesinUS table as follows
[WebMethod] public string[] GetCountryOrStatesInfo(string prefixText, int count, string contextKey)
{
  int count = 10; 
  string sql; 
  if (contextKey == "Country") 
    sql = "Select Country_Name from Country Where Country_Name like @prefixText"; 
  else 
    sql = "Select States_Name from States Where States_Name like @prefixText"; 

  SqlDataAdapter da = new SqlDataAdapter(sql,”Your connection String”); 
  da.SelectCommand.Parameters.Add("@prefixText",SqlDbType.VarChar, 50).Value = prefixText + "%"; 
  DataTable dt = new DataTable(); 
  da.Fill(dt); 

  string[] items = new string[dt.Rows.Count]; 
  int i = 0; 
  foreach (DataRow dr in dt.Rows) 
  { 
    items.SetValue(dr[0].ToString(), i); 
    i++; 
   } 

    return items;
}
The above webmethod takes 3 arguments such as prefixText, count and contextKey. So any method that uses contextKey must be with the above signature. The prefixText will pass the initial value entered in the AutoComplete TextBox, count will give the number of items returned to the popup menu of the TextBox and contextKey will be the additional parameter to be passed to the webmethod. So in the above sample webmethod, we pass the type of value to be displayed in the TextBox that is either Country of States.

Next, in the Default.aspx page, set the AutoCompleteExtender’s TargetControlID property to the TextBox Id. Now you can see a new Extenders Tab is added in the Textbox’s Property window. Set ServicePath as WebService.asmx, ServiceMethod as GetCountryOrStatesInfo and useContextKey to true. Specify the default values for contextKey as Country. The code for the AutoComplete Extender will be as follows
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" MinimumPrefixLength="1" ServiceMethod="GetCountryOrStatesInfo" UseContextKey="true" ContextKey="Country" ServicePath="WebService.asmx" TargetControlID="TextBox1"></cc1:AutoCompleteExtender>
Add a DropDownList control to this page, add items as List only Country and List only States. Specify its AutoPostback to true. On the OnSelectedIndexChanged event of the DropDownList, add the following code

AutoCompleteExtender1.ContextKey = cmbList.SelectedValue;
The code of the DropDownList control will be
<asp:DropDownList ID="cmbList" runat="server" AutoPostBack="True" OnSelectedIndexChanged="cmbList_SelectedIndexChanged"> <asp:ListItem Value="Country">List only Country</asp:ListItem> <asp:ListItem Value="States">List only States</asp:ListItem> </asp:DropDownList>
Save your project and run the application. You can see the AutoComplete TextBox and DropDownList control. Now type some letters in the TextBox, it will populate the corresponding countries. Next change the value in the DropDownList as List Only States, and type some letters in the TextBox it will populate the States from the starting letter you typed.

Click here to view our Sample AutoComplete with Additional Parameter
 
Viewer's Comments
Posted by alif on 9/10/2007 12:25:19 PM
Hello, Please, I have tried at many times to use your code for an auto complete text box from a database whithout any result ?! Could I have your email in order to send to you my code ? Thank you very much in advance.
 
Posted by alif on 9/10/2007 12:25:54 PM
my mail is alif@enst.fr
 
Posted by Mohan on 9/26/2007 1:16:05 PM
I have tried to use your code but could not get any output. Can I mail you my codepart
 
Posted by doulcat on 9/26/2007 4:20:13 PM
if you are using the newer version of the autocomplete, just click on the smart tag and it will generate the function in the default. The added webservice wasn't working for me neither. this is what i have for the extender, code is the same(had to delete the int count...) I do hav
 
Posted by doulcat on 9/26/2007 4:22:22 PM
i need to perform an action when the user selects one of the text value, is there an event that is fired? how would you perform this action?
 
Posted by naresh on 10/14/2007 5:38:19 PM
Hi I am getting undefined values in the div. Please help me Thanks in advance
 
Posted by Ganapathi on 10/15/2007 5:54:41 AM
How can i get the code in AutoCompleteExtender control
 
Posted by saju on 10/16/2007 2:41:56 PM
Excellent work
 
Posted by Satish on 10/19/2007 5:01:33 AM
Its too good......but i hav a query like once it fetches the matching characters can i make them bold or change the color of the items being fetched which matched the entered text ? Could anyone pls let me know if its possible and mail me....my id is satishash80@yahoo.co.in. Thanks in advance
 
Posted by Ajay on 11/13/2007 6:30:41 AM
Is that possible to implement this feature for HTML control instead of asp server control. As I have tried it ,but it did not work.So how can I implement it for HTML text box ,even runat server can be set as on.Any suggestion? Thanks & Regards Ajay K Dwivedi
 
Posted by jagan on 11/23/2007 10:46:35 PM
I have tried to use your code but could not get any output.autocomplete textbox is not working
 
Posted by konda reddy on 12/26/2007 1:34:36 AM
i am not getting reference (System.Web.Script.Services.ScriptService) iam getting upto System.Web.Script.Services only how to get rest of scriptservice
 
Posted by konda reddy on 12/26/2007 1:35:38 AM
excellent work but i am not getting System.Web.Script.Services.ScriptService but how to........
 
Posted by shagil on 12/27/2007 4:56:02 AM
I have tried many times but am getting error in web service code page. there is an error "string Items" part. can u pls mail ur code in to my ID. Am expecting a positive moment from ur side as soon as possible thanking you
 
Posted by Chris on 1/8/2008 2:17:20 PM
For those of you having problems with this, I have found that dragging a new instance of the control to the design surface usually fixed the "it's not working" problem. For some reason, if you create the control in source mode it does not pick up the changes.
 
Posted by usama on 1/17/2008 3:58:46 PM
excellent you solved my problem
 
Posted by usama on 1/17/2008 3:58:50 PM
excellent you solved my problem
 
Posted by girish on 1/18/2008 12:30:33 AM
excellent work you solved my problem
 
Posted by Ravi on 2/10/2008 2:48:08 AM
Hi I am working on an application in asp.net with c#. I am using the auto complete control for email field, i am swoing the existing email id list. After select the email from existing email id list, I want to resist the user to edit the selected email id in asp.net.
 
Posted by Ravindra on 2/18/2008 6:14:48 AM
I have written code to populate the values from database, it works fine on my local machine but when i am trying to populate it on server it doesn't throw exception but shoes all undefined or null values. Please help me i am working on this issue from last one week.
 
Posted by Canh on 2/28/2008 1:13:52 PM
L?n m? mày có tí code mà d?u nhu mèo d?u c?t. Fuck Your Mother.
 
Posted by Sandip on 3/14/2008 1:44:13 AM
If I write letter in a textbox then it will show all all string which starting from that letter using ajax how i do that?
 
Posted by Sandip on 3/14/2008 1:46:03 AM
bellow that text box suppose i write m then it will show mumbai,miraj,manglore etc.
 
Posted by raj on 5/27/2008 9:36:10 AM
this is bad article
 
Posted by in2minds on 5/30/2008 4:29:13 PM
Can you post the source code or email me the source code please?
 
Posted by Kavitha on 6/2/2008 4:05:25 AM
Can we do the same in .net textbox control without using AJAX. If possible how? Can you mail me.
 
Posted by John on 6/24/2008 11:03:27 PM
Excellent option using context key, never striked earlier using context key, I was struggling a lot to pass a additional parameter, it worked well for me Thank you. Very Good Article!!!
 
Posted by waste on 7/23/2008 8:51:15 AM
waste
 
Posted by Phi on 7/29/2008 10:22:14 PM
Your code does not work. Sorry mate. Try using session instead of the ContextKey. Here is vb code for the txtState combobox, for example Protected Sub txtState_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtState.SelectedIndexChanged Session("curState") = txtState.Text End Sub Then you can use this Session("curState") in AutoComplete.asmx.vb Good luck!
 
Posted by rajesh singh on 8/29/2008 9:44:37 AM
hi all, Please help me............. when enter one charecter into asp:textbox then debugger not move at the web services page ..... what is reason? TargetControlID,ServicePath and ServiceMethod, passing currect value.....
 
Posted by dotnet on 9/25/2008 1:12:45 PM
Hi, I did exactly same thing. But it is not working in my website although the xml file is generated. Do I need to do anything else except the things specified here?
 
Posted by mayhamm on 11/9/2008 4:56:12 PM
This REALLY helped me a lot! I had been using the AutoCompleteExtender and needed to add another parameter to my WebService Method based on the Users Location ID...I set the LocationID in the Session once the User logs in and set the AutoCompleteExtender.ContextKey in the Page_Load Event...Thanks again.
 
Posted by basil on 11/17/2008 4:44:36 AM
Good article. Anyway do you think it is possible to set the ContextKey with javascript so a postback to the server could be eliminated?
 
Posted by Samiam on 11/18/2008 5:54:10 PM
This is an excellent way to perform the auto complete of a text box. This is just what I was looking for I used it without the dropdown list. Thanks for the fine post.
 
Posted by selva on 12/1/2008 10:55:03 PM
Hi , i did Auto complete Text box in Grid ..it is working fine but i want auto complete textbox with multiple columns ...can anyone plz help me te resolve ...
 
Posted by john on 12/3/2008 12:46:20 AM
Hi, i tried to your coding but the textbox is not auto fill i used ajax 1.0 version in my coding is it work or not?
 
Posted by Ponprabhu on 1/22/2009 3:16:24 AM
I wish to use a AutoCompleteExtender for a TextBox, however, I wish the list to be populated only when user presses a special key (for example Enter key). Other than that, I wish to abort population without calling a postback to the server. Is that possible?
 
Posted by Deepak on 1/30/2009 6:37:49 AM
Hi I am new in asp.net i just want to make a textbox which shows all the matching words in popup window like when we write email add of someone if it is existing in my records it shows in popup window i am using ms acess db.
 
Posted by Paul Disse on 1/30/2009 4:01:08 PM
This example worked fantastic! I had been hung up for a while, but this seems to be a really quick way to populate the Textbox. I converted the code to VB, however.
 
Posted by suguna on 4/13/2009 1:35:24 AM
Hello, Please, I have tried at many times to use your code for an auto complete text box from a database whithout any result ?! Could I have your email in order to send to you my code ? Thank you very much in advance.
 
Posted by Amol Pandit on 4/20/2009 1:14:03 AM
I am just copy u r code in my application but it not working even it will not show any error whats wrong please help me.
 
Posted by helly on 4/24/2009 3:26:53 AM
This code is worked.and very useful to my application.
 
Posted by pau on 5/1/2009 1:16:12 PM
you've solved my boyfriend's problem! thanks!
 
Posted by Anon on 5/6/2009 3:08:19 AM
I find it quite funny that you are all commenting on the poor article code. If you are Developers work it out instead of complaining! there are hundreds of Ajax articles out there, lol
 
Posted by saikrishna on 5/15/2009 9:23:00 AM
Pls help me out. I want to send additonal parameter to webservice which searches along with prefix but the problem is I CANT FIND ContextKey . I am using vs.net 2005 and .NET 2.0. Pls help . I have been searching a lot
 
Posted by Rawson on 6/9/2009 8:16:03 AM
Excellent article, exactly what I was looking for!
 
Posted by salinee sachan on 6/22/2009 2:29:30 AM
I have used yr code but it gives error "'AjaxControlToolkit.AutoCompleteExtender' does not have a public property named 'UseContextKey" i'm using visual web devloper 2008 plz help
 
Posted by Divya on 7/18/2009 4:26:28 AM
Superb..its help me alot
 
Posted by srinu.m on 7/18/2009 4:40:14 AM
I have got excellent o/p's from u r web site. thaq very much.
 
Posted by Sanam on 8/18/2009 8:09:18 AM
Friend This is not working in my case please send one program example to my mail Thanks in advance Sanam
 
Posted by scptech on 9/18/2009 1:58:27 PM
Thank you for the example. Can it be extended to populate multiple textbozes? For example, when searching for a client, populate 3 textboxes, with the name, date of birth and clientId from the database?
 
Posted by Goran on 9/23/2009 8:55:19 AM
There is an erro in the code. I am sure people have noticed but int count = 10; No Good. count is passed with the function call...
 
Posted by Leima on 10/12/2009 1:30:35 PM
Thank very much, I already had the autocomplete but I didnt know how to send extra parameters, your code worked great for that purpose
 
Posted by Dibyendu on 10/22/2009 6:02:44 AM
Your code is not working.. bad code
 
Posted by RAc on 10/29/2009 8:06:30 PM
Is it possible to send 2 o more parameters like ContextKey ? I Have this case, @prefixText - for autocomplete name of the employee @count - for the number of ocurrences @ContextKey - for IDCountry (Context Key Param1) additionally i need other param like ContextKey @IDStore - Key of the store (Context Key Param2) Autocomplete works with complex SQL or only with 1 parameter??? Thanks
 
Posted by Ralph on 11/9/2009 7:29:53 AM
for those who cannot get this to work : - when you write your web method 'ContextKey' is case SeNsiItve! that should fix it!
 
Posted by subha on 12/16/2009 12:11:19 AM
hai all, how to send hyperlink field in Autocomplete extender textbox,canu help me
 
Posted by gayathri on 12/16/2009 12:13:58 AM
hai all, i need to pass linkbutton in auto complete extender textbox,if u know pls send code,very urgent
 
Posted by c on 1/14/2010 1:50:07 AM
hi all, i have a problem here, i tried to include another function to retrieve from another table but it cant work. only the 1st function is working the 2nd not working
 
Posted by vanchinathan on 5/18/2010 3:00:08 AM
it is very usefull. also tell me like below hi pls tell me. i have three textboxes(txtkeywords,txtArea,txtPincode) and i have three autocomplete extender for that all. i need to add the autocomplete extender for these three textboxes. each textboxes values are from different column of different table. and each boxes having different methods.
 
Posted by ramaniranjan on 6/2/2010 6:49:50 AM
I want auto fill textbox without java script and ajax in asp.net 2.0 if I am put first latter of the company name then show me available company name starting form this latter
 
Posted by Ravish on 6/8/2010 12:13:42 PM
it is very usefull. also tell me like below hi pls tell me. i have three textboxes(txtkeywords,txtArea,txtPincode) and i have three autocomplete extender for that all. i need to add the autocomplete extender for these three textboxes. each textboxes values are from different column of different table. and each boxes having different methods
 
Posted by Ravish on 6/8/2010 12:13:59 PM
it is very usefull. also tell me like below hi pls tell me. i have three textboxes(txtkeywords,txtArea,txtPincode) and i have three autocomplete extender for that all. i need to add the autocomplete extender for these three textboxes. each textboxes values are from different column of different table. and each boxes having different methods
 
Posted by rajesh on 6/9/2010 3:28:25 AM
this is very nice code
 
Posted by Avijit Datta on 7/15/2010 3:18:59 AM
Hi, U jst make my day... Thanks a lot for this post. Ultimate. Just one thing how could I pass multiple parameter to web service? Thanks in advance.
 
Posted by SUDHEER on 7/26/2010 10:19:23 AM
Thanks !!
 
Posted by Murali on 8/21/2010 6:58:05 AM
How Can I use Autoextender when I am Typing in Text Box focus is on Grid .
 
Posted by Kat on 10/25/2010 7:03:56 PM
Hi, I have an autocomplete extender in a user control. In the control are 2 dropdowns (in update panels) and the extender associated textbox. The contextKey is correctly updated in the usercontrol on selectedIndexChanged and initially set when !IsPostBack (ie: contextKey set in codebehind). The web method is defined in the page that holds the user control and is called correctly. Problem is that even though the control contextKey is updated, when the web method is called the contextKe
 
Posted by atul on 1/5/2011 3:15:29 AM
hi thanks, this code is very useful for me but i have some problem in this code ,i am use label and textbox and auotocomplete extender use on textbox and dropdown is replace by label and label should be bind by grid on bind grid function . i am confuse which data transfer in context key and how to pass this code in label . please give me a suggestion urgently
 
Posted by Lakshmi on 1/19/2011 10:52:41 AM
hi u r code is k but am trying like this am using xml in that dropdownlist foru xml files are there how to pass context key when am selecting one xml file i.e in runtime please give me a suggestion urgently
 
Posted by Lakshmi on 1/19/2011 10:52:45 AM
hi u r code is k but am trying like this am using xml in that dropdownlist foru xml files are there how to pass context key when am selecting one xml file i.e in runtime please give me a suggestion urgently
 
Posted by Amit on 1/25/2011 1:25:30 AM
thanksssssssssssssssssssssssssssssssssssssssssssssssss mannnnn
 
Posted by wang on 2/13/2011 12:48:32 AM
prefect code! not work should check : 1.int count = 10; //Unnecessary 2.check your sql; 3. new project must be website , if web application this will not work; this is improtant~!!
 
Posted by prasanth on 3/11/2011 1:16:54 AM
I have two text boxes with each one has auto complete text box extender.Based On First text box value ,i am getting second text box values.it is working fine .But my problem is old values are remaining in second text box (like intellisence) sample : textBox1 Value is A -- textBox2 values are a1,a2 ....Suppose i changed textBox1 Value to B -- textBox2 values are a1,a2,b1,b2 (i expected only b1,b2)
 
Posted by pankaj dixit on 4/28/2011 8:02:46 AM
Thanks ! Yes its Working
 
Posted by MSP on 7/13/2011 10:47:41 AM
Excellent! I was looking for this solution. ThankQ!!!
 
Posted by MSP on 7/13/2011 10:50:28 AM
Wonderful article and solution. Thank you very much!
 
Posted by Anonymous on 8/7/2011 4:35:54 PM
nice one mate
 
Posted by Anil on 10/15/2011 5:06:00 AM
I want to pass a session id to WebService.asmx..how is it done?
 
Posted by RBS on 2/7/2012 4:17:08 AM
Hi, I wanna create a code for the following- when anyone type some letters the there in the text box, autocomplete option would be show and when He click any entry of them, then some results are shown related to that name like when we type in Google's text box.
 
Posted by gie on 4/16/2012 7:53:17 PM
rajesh singh "hi all, Please help me............. when enter one charecter into asp:textbox then debugger not move at the web services page ..... what is reason? TargetControlID,ServicePath and ServiceMethod, passing currect value....." did this question got answered??? i have the save problem here and i dont know what to do can anybody help me pleeeaaassseeee...
 
Posted by Krunal on 6/5/2012 9:16:23 AM
HI, Thanks for this article. It has given me the solution.
 
Posted by lakshmikanthreddy on 11/14/2013 4:25:32 AM
Thank but i need same the gridview , as different coloumns in the gridview , please help in this case..
 
Posted by abhi on 2/12/2014 1:15:10 AM
ContextKey value not cleared previous value for example dropdown selectindexchanged event we have set contextkey value but it shows previous selectindexchanged value
 
Posted by abhi on 2/12/2014 1:16:02 AM
give me reply as soon as possible
 
 Rating & Comments
A word 'Excellent' means lot to the author of this article. You can give comments about this article but not the author.
Rate this Article:
Name:
Email Id:  
We never display your email id anywhere.
Comment/Question: Max. 500 letters
Five plus Ninety Equals To
 
Sponsored by
The Beginner's Guide to Joomla
Backup and Recovery Best Practices for Microsoft SQL Server 2005
Web Application Security — How to Minimize Prevalent Risk of Attacks