AspdotnetCodes.com
Voted 'Best ASP.NET Host' for 2008 – DiscountASP.NET
 
Articles Subscribe for our Articles Updates
Books
Resources
Downloads
Free Tech Magazines
Archives
Softwares
Newsletter
Suggest Us
Link to Us
 AutoComplete Textbox with Additional Parameters From Database
Posted by Moderator1 on 7/23/2007 11:16:01 PM Category: AJAX
Total Views : 20246
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 Reginaldo on 8/12/2008 11:53:39 AM
Otima dica, muito obrigado pela ajuda.
 
 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
 
Sponsored by