In this article I will explain how to make use of ASP.Net AJAX Control Toolkit Cascading DropDown with DropDownLists control inside ASP.Net GridView. Two AJAX Cascading Dropdowns along with the two corresponding ASP.Net DropDownLists will be populated from database with values of Country and City using Web Service and Web Methods.
On Page Load list of Countries is populated, when Country is selected and when a State is chosen list of Cities will be populated, thus at the end we get a Country City Cascading DropDownLists implemented using ASP.Net AJAX Cascading DropDown control in GridView.
 
 
Database
For database I am using the Microsoft’s Northwind Database. You can download the same using the link below
 
 
Using the ASP.Net AJAX Control Toolkit CascadingDropDown Control
1. Register the AJAX Control Toolkit Library after adding reference to your project
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
 
2. Drag an ASP.Net AJAX ToolScriptManager on the page.
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</cc1:ToolkitScriptManager>
 
3. Then you need to add the AJAX CascadingDropDown control next to the DropDownList control for which you want to use as Cascading DropDownList.
<asp:DropDownList ID="ddlCountries" runat="server" Width = "150">
</asp:DropDownList>
<cc1:CascadingDropDown ID="cdlCountries" TargetControlID="ddlCountries" PromptText="Select Country" PromptValue="" ServicePath="ServiceCS.asmx" ServiceMethod="GetCountries" runat="server" Category="CountryId" />
 
 
HTML Markup
The HTML Markup consists of a GridView control with two ASP.Net DropDownLists along with their corresponding three ASP.Net AJAX CascadingDropDowns.
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePageMethods="true">
</cc1:ToolkitScriptManager>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField HeaderText="Name" DataField="ContactName" />
        <asp:TemplateField HeaderText="Country">
            <ItemTemplate>
                <asp:DropDownList ID="ddlCountries" runat="server" Width = "150">
                </asp:DropDownList>
                <cc1:CascadingDropDown ID="cdlCountries" TargetControlID="ddlCountries" PromptText = "Select Country" PromptValue = ""
                    ServicePath = "ServiceCS.asmx" ServiceMethod="GetCountries"
                    runat="server" Category="Country" />
            </ItemTemplate>
        </asp:TemplateField>
            <asp:TemplateField HeaderText="City">
            <ItemTemplate>
                <asp:DropDownList ID="ddlCities" runat="server" Width = "150">
                </asp:DropDownList>
                <cc1:CascadingDropDown ID = "cdlCities" TargetControlID="ddlCities" PromptText = "Select City" PromptValue = ""
                    ServicePath = "ServiceCS.asmx" ServiceMethod="GetCities" runat="server"
                    Category="City" ParentControlID = "ddlCountries" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
 
 
CascadingDropDown Properties
Below are some important properties of the AJAX CascadingDropDown
TargetControlID – Here we need to set the ID of the DropDownList control for which you want to make an AJAX Cascading DropDownList.
ServicePath – Here we set the URL of the Web Service that will act as source of data for the AJAX CascadingDropDown DropDownList.
ServiceMethod – Here we set the name of the Web Method that will be used to populate the AJAX CascadingDropDown DropDownList.
PromptText – This property is the Text part that of the first or the default item that will be displayed in the AJAX CascadingDropDown DropDownList.
PromptValue – This property is the Value part that of the first or the default item that will be displayed in the AJAX CascadingDropDown DropDownList.
Category – This property is used to specify the Category for the AJAX CascadingDropDown DropDownList, Category value is passed as parameter to the Child or dependent AJAX CascadingDropDown DropDownList ServiceMethod i.e. Web Method.
ParentControlID – This property is used to set the ID of the DropDownList on whose selection the DropDownList will trigger the data population process.
LoadingText– This property used to display the loading text when the call is made to the Web Method until the data is populated in the AJAX CascadingDropDown DropDownList.
 
 
Binding the GridView
In the page load event of the page, I am populating the GridView with records from Customers table of the Northwind Database.
C#
Namespaces
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
 
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GridView1.DataSource = GetData("SELECT TOP 10 ContactName, Country FROM Customers");
        GridView1.DataBind();
    }
}
 
private DataSet GetData(string query)
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
 
            sda.SelectCommand = cmd;
            using (DataSet ds = new DataSet())
            {
                sda.Fill(ds);
                return ds;
            }
        }
    }
}
 
VB.Net
Namespaces
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        GridView1.DataSource = GetData("SELECT TOP 10 ContactName, Country FROM Customers")
        GridView1.DataBind()
    End If
End Sub
 
Private Function GetData(query As String) As DataSet
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim cmd As New SqlCommand(query)
    Using con As New SqlConnection(conString)
        Using sda As New SqlDataAdapter()
            cmd.Connection = con
 
            sda.SelectCommand = cmd
            Using ds As New DataSet()
                sda.Fill(ds)
                Return ds
            End Using
        End Using
    End Using
End Function
 
 
Web Service for handing CascadingDropDown AJAX Calls
Below is the code of the Web Service that will act as the source of data for the ASP.Net AJAX CascadingDropDown DropDownLists. There are two Web Methods in the Web Service, one for each AJAX CascadingDropDown i.e. Country and City.
Both the two Web Methods accept knownCategoryValues as parameter, which is nothing but combination of the Category and the Selected Value from the Parent DropDownList. For example for the Country AJAX CascadingDropDown the value of knownCategoryValues looks like CountryId: Austria; where CountryId is the Category specified of the Country DropDownList
If the CascadingDropDown does not have any parent then the knownCategoryValues is blank.
The return type of each Web Method is an Array of CascadingDropDownNameValue class objects, which belongs to the AJAX Control Toolkit namespace.
Each of the three Web Methods get the records from database through a generic function named as GetData which returns the fetched item as an Array of CascadingDropDownNameValue class objects after fetching records from database using DataReader.
C#
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using AjaxControlToolkit;
 
///<summary>
/// Summary description for ServiceCS
///</summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ServiceCS : System.Web.Services.WebService
{
    [WebMethod]
    public CascadingDropDownNameValue[] GetCountries(string knownCategoryValues)
    {
        string query = "SELECT DISTINCT Country FROM Customers";
        List<CascadingDropDownNameValue> countries = GetData(query);
        return countries.ToArray();
    }
 
    [WebMethod]
    public CascadingDropDownNameValue[] GetCities(string knownCategoryValues)
    {
        string country = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)["Country"];
        string query = string.Format("SELECT DISTINCT City FROM Customers WHERE Country = '{0}'", country);
        List<CascadingDropDownNameValue> cities = GetData(query);
        return cities.ToArray();
    }
 
    private List<CascadingDropDownNameValue> GetData(string query)
    {
        string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        SqlCommand cmd = new SqlCommand(query);
        List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();
        using (SqlConnection con = new SqlConnection(conString))
        {
            con.Open();
            cmd.Connection = con;
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    values.Add(new CascadingDropDownNameValue
                    {
                        name = reader[0].ToString(),
                        value = reader[0].ToString()
                    });
                }
                reader.Close();
                con.Close();
                return values;
            }
        }
    }
}
 
VB.Net
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports AjaxControlToolkit
Imports System.Collections.Generic
 
<WebService([Namespace]:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<System.Web.Script.Services.ScriptService()> _
Public Class ServiceVB
    Inherits System.Web.Services.WebService
    <WebMethod()> _
    Public Function GetCountries(knownCategoryValues As String) As CascadingDropDownNameValue()
        Dim query As String = "SELECT DISTINCT Country FROM Customers"
        Dim countries As List(Of CascadingDropDownNameValue) = GetData(query)
        Return countries.ToArray()
    End Function
 
    <WebMethod()> _
    Public Function GetCities(knownCategoryValues As String) As CascadingDropDownNameValue()
        Dim country As String = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)("Country")
        Dim query As String = String.Format("SELECT DISTINCT City FROM Customers WHERE Country = '{0}'", country)
        Dim cities As List(Of CascadingDropDownNameValue) = GetData(query)
        Return cities.ToArray()
    End Function
 
    Private Function GetData(query As String) As List(Of CascadingDropDownNameValue)
        Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim cmd As New SqlCommand(query)
        Dim values As New List(Of CascadingDropDownNameValue)()
        Using con As New SqlConnection(conString)
            con.Open()
            cmd.Connection = con
            Using reader As SqlDataReader = cmd.ExecuteReader()
                While reader.Read()
                    values.Add(New CascadingDropDownNameValue() With { _
                     .name = reader(0).ToString(), _
                     .value = reader(0).ToString() _
                    })
                End While
                reader.Close()
                con.Close()
                Return values
            End Using
        End Using
    End Function
End Class
 
Implement AJAX Cascading DropDown with DropDownList in GridView in ASP.Net
 
 
Demo
 
 
Downloads