Home > AJAX, ASP.Net, AutoCompleteExtender, Java Script > Dynamically set the AutoCompleteExtender ContextKey

Dynamically set the AutoCompleteExtender ContextKey


Hi All,

Here in this article I will be explaining How to set and use AutocompleteExtender’s ContextKey Dynamically to Load the data based on some condition. I am assuming that you know how to use AutoCompleteExtender Control of AJAX toolkit (Please refer this link for basic info).

Basically this post is helpful for the below given problem.

Senerio – Let’s assume there is a textbox where we implement autocompleteExtender to load Countries List, and there is one more textbox for state but in state textbox we want to load the state list based on country selected in first Textbox.

To overcome with the above problem we need to use ContextKey and need to change it dynamically.

Here is the example

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MSCoderAutoCompleteKeyValuePair._Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript" language="javascript">
        function SetCountryID(source, eventArgs) {
            $find('StateAutoComplete').set_contextKey(eventArgs.get_value());
        }        
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <table>
        <tr>
            <td>
                Country
            </td>
            <td>
                <cc1:AutoCompleteExtender ID="CountryAutoComplete" runat="server" TargetControlID="txtCountry"
                    EnableCaching="false" CompletionSetCount="20" MinimumPrefixLength="1" ServicePath="wsAutoCompleteService.asmx"
                    FirstRowSelected="true" ServiceMethod="GetCountriesList" OnClientItemSelected="SetCountryID" />
                <asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td>
                State
            </td>
            <td>
                <cc1:AutoCompleteExtender ID="StateAutoComplete" runat="server" TargetControlID="txtState"
                    EnableCaching="false" MinimumPrefixLength="1" ServicePath="wsAutoCompleteService.asmx"
                    FirstRowSelected="true" ServiceMethod="GetStatesList" />
                <asp:TextBox ID="txtState" runat="server"></asp:TextBox>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

 

Webservice to fetch the data from the Database

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;

namespace MSCoderAutoCompleteKeyValuePair
{
    /// <summary>
    /// Summary description for AutoCompleteService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX 
    [System.Web.Script.Services.ScriptService]
    public class AutoCompleteService : System.Web.Services.WebService
    {
        /// <summary>
        /// Method to get Countries List
        /// </summary>
        /// <param name="prefixText"></param>
        /// <param name="count"></param>
        /// <returns>String array which contains Countries name</returns>
        [WebMethod(true)]
        public string[] GetCountriesList(string prefixText, int count)
        {
            if (count == 0)
                count = 10;

            List<String> result = new List<string>();
            using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand(string.Format("Select Top {0} ID,Name from CountryTable Where Name Like '{1}%'",count, prefixText), connection);
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        result.Add(AutoCompleteItem(Convert.ToString(reader["Name"]), Convert.ToString(reader["ID"])));
                    }
                }            
            }
            return result.ToArray();
        }

        /// <summary>
        /// Method to get States List
        /// </summary>
        /// <param name="prefixText"></param>
        /// <param name="count"></param>
        /// <param name="contextKey"></param>
        /// <returns>String array which contains States name</returns>
        [WebMethod(true)]
        public string[] GetStatesList(string prefixText, int count,string contextKey)
        {
            List<String> result = new List<string>();
            using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand(string.Format("Select Top {0} ID,Name from StateTable Where Name Like '{1}%' And CountryID={2}", count, prefixText, contextKey), connection);
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader != null)
                {
                    while (reader.Read())
                    {
                        result.Add(AutoCompleteItem(Convert.ToString(reader["Name"]), Convert.ToString(reader["ID"])));
                    }
                }
            }
            return result.ToArray();
        }

        /// <summary>
        /// Method to get Formatted String value which can be used for KeyValue Pair for AutoCompleteExtender
        /// </summary>
        /// <param name="value"></param>
        /// <param name="id"></param>
        /// <returns>Returns string value which holds key and value in a specific format</returns>
        private string AutoCompleteItem(string value, string id)
        {
            return string.Format("{{\"First\":\"{0}\",\"Second\":\"{1}\"}}", value, id);
        }
    }
}

 

Code Behind file which contains nothing

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MSCoderAutoCompleteKeyValuePair
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }
    }
}

When we select India in Country textbox then in state textbox all the India’s states will get listed and when we select USA as a country then USA’s states will be listed.

image

image

SQL Script for the Database

Create Database [Database]
Go
USE [Database]
Go
CREATE TABLE CountryTable(
    [ID] int NOT NULL Primary key,
    [Name] varchar(50) NOT NULL
)
Go
CREATE TABLE StateTable(
    [ID] int NOT NULL Primary key,
    [CountryID] int NOT NULL,
    [Name] varchar(50) NOT NULL
)
Go
Insert Into CountryTable Values(1,'India')
Insert Into CountryTable Values(2,'USA')
Insert Into StateTable Values(1,1, 'Andhra Pradesh')
Insert Into StateTable Values(2,1, 'Arunachal Pradesh')
Insert Into StateTable Values(3,1, 'Assam')
Insert Into StateTable Values(4,1, 'Bihar')
Insert Into StateTable Values(5,1, 'Chhattisgarh')
Insert Into StateTable Values(6,1, 'Goa')
Insert Into StateTable Values(7,1, 'Gujarat')
Insert Into StateTable Values(8,1, 'Haryana')
Insert Into StateTable Values(9,1, 'Himachal Pradesh')
Insert Into StateTable Values(10,1, 'Jammu and Kashmir')
Insert Into StateTable Values(11,1, 'Jharkhand')
Insert Into StateTable Values(12,1, 'Karnataka')
Insert Into StateTable Values(13,1, 'Kerala')
Insert Into StateTable Values(14,1, 'Madhya Pradesh')
Insert Into StateTable Values(15,1, 'Maharashtra')
Insert Into StateTable Values(16,1, 'Manipur')
Insert Into StateTable Values(17,1, 'Meghalaya')
Insert Into StateTable Values(18,1, 'Mizoram')
Insert Into StateTable Values(19,1, 'Nagaland')
Insert Into StateTable Values(20,1, 'Orissa')
Insert Into StateTable Values(21,1, 'Punjab')
Insert Into StateTable Values(22,1, 'Rajasthan')
Insert Into StateTable Values(23,1, 'Sikkim')
Insert Into StateTable Values(24,1, 'Tamil Nadu')
Insert Into StateTable Values(25,1, 'Tripura')
Insert Into StateTable Values(26,1, 'Uttar Pradesh')
Insert Into StateTable Values(27,1, 'Uttarakhand')
Insert Into StateTable Values(28,1, 'West Bengal')
Insert Into StateTable Values(29,2, 'Alabama')
Insert Into StateTable Values(30,2, 'Alaska')
Insert Into StateTable Values(31,2, 'Arizona')
Insert Into StateTable Values(32,2, 'Arkansas')
Insert Into StateTable Values(33,2, 'California')
Insert Into StateTable Values(34,2, 'Colorado')
Insert Into StateTable Values(35,2, 'Connecticut')
Insert Into StateTable Values(36,2, 'Delaware')
Insert Into StateTable Values(37,2, 'Florida')
Insert Into StateTable Values(38,2, 'Georgia')
Insert Into StateTable Values(39,2, 'Hawaii')
Insert Into StateTable Values(40,2, 'Idaho')
Insert Into StateTable Values(41,2, 'Illinois')
Insert Into StateTable Values(42,2, 'Indiana')
Insert Into StateTable Values(43,2, 'Iowa')
Insert Into StateTable Values(44,2, 'Kansas')
Insert Into StateTable Values(45,2, 'Kentucky')
Insert Into StateTable Values(46,2, 'Louisiana')
Insert Into StateTable Values(47,2, 'Maine')
Insert Into StateTable Values(48,2, 'Maryland')
Insert Into StateTable Values(49,2, 'Massachusetts')
Insert Into StateTable Values(50,2, 'Michigan')
Insert Into StateTable Values(51,2, 'Minnesota')
Insert Into StateTable Values(52,2, 'Mississippi')
Insert Into StateTable Values(53,2, 'Missouri')
Insert Into StateTable Values(54,2, 'Montana')
Insert Into StateTable Values(55,2, 'Nebraska')
Insert Into StateTable Values(56,2, 'Nevada')
Insert Into StateTable Values(57,2, 'New Hampshire')
Insert Into StateTable Values(58,2, 'New Jersey')
Insert Into StateTable Values(59,2, 'New Mexico')
Insert Into StateTable Values(60,2, 'New York')
Insert Into StateTable Values(61,2, 'North Carolina')
Insert Into StateTable Values(62,2, 'North Dakota')
Insert Into StateTable Values(63,2, 'Ohio')
Insert Into StateTable Values(64,2, 'Oklahoma')
Insert Into StateTable Values(65,2, 'Oregon')
Insert Into StateTable Values(66,2, 'Pennsylvania')
Insert Into StateTable Values(67,2, 'Rhode Island')
Insert Into StateTable Values(68,2, 'South Carolina')
Insert Into StateTable Values(69,2, 'South Dakota')
Insert Into StateTable Values(70,2, 'Tennessee')
Insert Into StateTable Values(71,2, 'Texas')
Insert Into StateTable Values(72,2, 'Utah')
Insert Into StateTable Values(73,2, 'Vermont')
Insert Into StateTable Values(74,2, 'Virginia')
Insert Into StateTable Values(75,2, 'Washington')
Insert Into StateTable Values(76,2, 'West Virginia')
Insert Into StateTable Values(77,2, 'Wisconsin')
Insert Into StateTable Values(78,2, 'Wyo')

Link to Download the Code.

If you have any query on it Please leave a Comment.

About these ads
  1. RAKESH
    July 8, 2010 at 1:09 PM

    Hey im getting some error that Error 3 Could not load type ‘MSCoderAutoCompleteKeyValuePair._Default’. C:\Documents and Settings\rakesh.p\My Documents\Visual Studio 2008\WebSites\WebSite6\Default.aspx 1

    • mscoder
      July 8, 2010 at 7:40 PM

      Hi Rakesh,

      This error arises when we have multiple versions of .NET Framework installed in our machine and default framework is not set in IIS.

      Follow below steps to set default .NET framework in IIS.

      Open Command Prompt
      Navigate to C:\Windows\Microsoft.NET\Framework\v2.0.50727\
      Type aspnet_regiis.exe -i
      Hit enter key.

      Thanks
      Surya

  2. satya
    August 27, 2010 at 4:06 PM

    Hi,

    If my web service is taking more time like 1 min then it is not showing any data in listbox. Any idea.

    Thanks
    Satya

  3. satya
    August 27, 2010 at 4:07 PM

    Hi,

    MY web service is taking moer time to return the results. In this case the autoextender is not shoiwng any data.

    ANy idea.

    Thanks
    Satya

  4. SD
    October 9, 2010 at 6:53 PM

    I have used contextkey, but I am not able to see any changes here with I have given the code, please check and let me know

    I have also assigned value to contextkey in server side code.

    [WebMethod]
    public string[] GetProduct_Article(string prefixText)
    {
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[“TridentConnectionString”].ToString());
    con.Open();
    SqlCommand cmd = new SqlCommand(“select pa from productarticle where pa LIKE ‘” + prefixText + “%’ “, con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);

    DataTable dt = new DataTable();
    da.Fill(dt);
    string[] items = new string[dt.Rows.Count];
    int i = 0;
    foreach (DataRow dr in dt.Rows)
    {
    items[i] = “\”” + dt.Rows[i][“pa”].ToString() + “\””;
    i++;

    }
    return items;
    }

    • MSCoder
      October 12, 2010 at 10:27 AM

      Hi
      Check your service whether [System.Web.Script.Services.ScriptService] attribute is added or not.

      If not then add it like this

      [System.Web.Script.Services.ScriptService]
      public class MyService : System.Web.Services.WebService
      {
      [WebMethod]
      public string[] GetProduct_Article(string prefixText)
      {
      //your Code
      }
      }

      and replace
      items[i] = “\”” + dt.Rows[i][“pa”].ToString() + “\””;
      with
      items[i] = dt.Rows[i][“pa”].ToString();

      Thanks

      MSCoder

  5. stephany henrique
    April 9, 2011 at 11:00 AM

    Parabéns, muito bom exemplo.

    Estava com este problema e o seu exemplo solucionou. Não posso deixar de agradecer por isso.

  6. Muthukrishnan
    March 12, 2012 at 3:46 PM

    superb..very helpful url for us…….

  7. Sonal Gawde
    June 11, 2012 at 6:06 PM

    Very Superb Article….. I did only one little change instead of $find(‘StateAutoComplete’).set_contextKey(eventArgs.get_value()); i wrote as follows
    $find(”).set_contextKey(eventArgs.get_value());

    • Sonal Gawde
      June 11, 2012 at 6:07 PM

      Very Superb Article….. I did only one little change instead of $find(‘StateAutoComplete’).set_contextKey(eventArgs.get_value()); i wrote as follows
      $find(”).set_contextKey(eventArgs.get_value());

  8. shambhu
    June 12, 2012 at 2:04 PM

    very very thanx for nice article

  9. Gaurav Agarwal
    May 31, 2013 at 9:59 AM

    hey i have more then 2 country in my database..then what would be changes in code?

  1. September 11, 2012 at 9:26 PM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: