Cascading dropdownlists in asp.net using ajaxControl tool kit

In as you have installed ajaxControl tool kit in your VS2005. Now let us start using it. In this article, I 'll show you how to make cascading dropdownlists by using ajaxControlToolkit For making cascading dropdownlists, make database either in SqlServer or in MS Access, Here I am using MS Access.Make two tables in Ms access database one for States and other for cities. In state table take two fields

id    autonumber
state Text

Save this table with name states and enter some data in state column Like

Goa
Kerala
Maharashtra

Make next table with following fileds

id        autonumber
sateid    number
city      text

save this table with name cities. Enter some cities' name in city column and enter corresponding state's id in
sateid column as given below.

stateid  city
1         Anjuna
1         Baga
3         Aurangabad
3         Mumbai
3         Pune
2        Cochin
2        Munnar

Now start new website project with option Ajax Control Toolkit WebSite. save with name cascading dropdownlists.Open default.aspx page's source. Write code for dropdown lists.

       Sates <asp:DropDownList ID="ddlSates" runat="server"></asp:DropDownList><br />
       Cities <asp:DropDownList ID="ddlCities" runat="server"></asp:DropDownList><br />


Open solution explorer right click on solution path, select Add ASP.NET Folder then click on App_Data. A Folder  with name App_Data will be created. Right Click on this folder then select Add Existing Item option.Browse your MS access file which you have made earlier and Select this file and click on Add Button. This willadd database file in your solution.Now click on Website menu and then select add new iten or use short cut (Ctrl+shift+A).Add New Item will appear, select WebService and click on Add button.By doing this WebService.asmx file and WebService.cs (In App_Code Folder) will be added.Open WebService.cs file and you will find auto genrateded code as given below.

 

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;


/// 
/// Summary description for WebService2
/// 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;


/// 
/// Summary description for WebService2
/// 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

 

 

 

Add some namespaces   as given below.

 

using System.Collections.Specialized;
using AjaxControlToolkit;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;


 


and write attribute System.Web.Script.Services.ScriptService before WebService class

 


using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Specialized;
using AjaxControlToolkit;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;

/// 
/// Summary description for WebService2
/// 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[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 string HelloWorld() {
        return "Hello World";
    }
    
}


//Now write WebMethods for populating dropdownlists in WebService class


    [System.Web.Script.Services.ScriptMethod]
    [WebMethod]
    public CascadingDropDownNameValue[] GetSates(string knownCategoryValues,string category)
    {
        OleDbConnection con = 
new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=|DataDirectory|Database.mdb;Persist Security Info=True");
        OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from sates",con);
        DataTable table = new DataTable();
        adapter.Fill(table);
        List values=
new List();
        foreach (DataRow dr in table.Rows)
        {  // for state column

            string state = (string)dr["state"];  
            int sateId = (int)dr["id"];
            values.Add(new CascadingDropDownNameValue(state , sateId.ToString()));
        }
        return values.ToArray();
    }

 

    [System.Web.Script.Services.ScriptMethod]
    [WebMethod]
    public CascadingDropDownNameValue[] GetCities(string knownCategoryValues,string category)
    {
        StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        int stateId;
        if (!kv.ContainsKey("state") || !Int32.TryParse(kv["state"], out stateId))
        {
            return null;
        }
        OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;
       Data Source=|DataDirectory|Database.mdb;Persist Security Info=True");
        OleDbDataAdapter adapter = new 
OleDbDataAdapter("Select * from cities where stateid="+stateId, con);
        DataTable table = new DataTable();
        adapter.Fill(table);

        List values
        =new List();
        foreach (DataRow dr in table.Rows)
        {
            values.Add(new CascadingDropDownNameValue(
         (string)dr["city"], dr["id"].ToString()));
        }
        return values.ToArray();
    }







 

 

As a whole

 

 

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Specialized;
using AjaxControlToolkit;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;

/// 
/// Summary description for WebService2
/// 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line 
        //if using designed components 
        //InitializeComponent(); 
    }

 

    [System.Web.Script.Services.ScriptMethod]
    [WebMethod]
    public CascadingDropDownNameValue[] GetSates(string knownCategoryValues,string category)
    {
        OleDbConnection con = new
 OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;
       Data Source=|DataDirectory|Database.mdb;Persist Security Info=True");
        OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from sates",con);
        DataTable table = new DataTable();
        adapter.Fill(table);
        List values=
        new List();
        foreach (DataRow dr in table.Rows)
        {
            string state = (string)dr["state"];  // for state column
            int sateId = (int)dr["id"];
            values.Add(new CascadingDropDownNameValue(state , sateId.ToString()));
        }
        return values.ToArray();
    }

 

    [System.Web.Script.Services.ScriptMethod]
    [WebMethod]
    public CascadingDropDownNameValue[] GetCities(string knownCategoryValues,string category)
    {
        StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        int stateId;
        if (!kv.ContainsKey("state") || !Int32.TryParse(kv["state"], out stateId))
        {
            return null;
        }
        OleDbConnection con = new 
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=|DataDirectory|Database.mdb;Persist Security Info=True");
        OleDbDataAdapter adapter = new 
OleDbDataAdapter("Select * from cities where stateid="+stateId, con);
        DataTable table = new DataTable();
        adapter.Fill(table);

        List values =
        new List();
        foreach (DataRow dr in table.Rows)
        {
            values.Add(new CascadingDropDownNameValue((string)dr["city"], dr["id"].ToString()));
        }
        return values.ToArray();
    }


    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }
    
}





 

 

after finishing class making move to default.aspx page open its source and write extenders in as given.

       Sates <asp:DropDownList ID="ddlSates" runat="server"></asp:DropDownList><br />
       Cities <asp:DropDownList ID="ddlCities" runat="server"></asp:DropDownLis><br/>

      <ajaxToolkit:CascadingDropDown
                ID="CascadingDropDown1"
                runat="server"
                TargetControlID="ddlSates"   <%--Id of dropdwon in which states will be shown--%>
                Category="state"  
                PromptText="Select a State"
                ServicePath="WebService.asmx" 
                ServiceMethod="GetSates" />   <%--WebService Method name--%>
        <ajaxToolkit:CascadingDropDown
                ID="CascadingDropDown2"
                runat="server"
                TargetControlID="ddlCities"     <%--Id of dropdwon in which cities will be shown--%>
                ParentControlID="ddlSates"
                PromptText="Please select a City"
                ServiceMethod="GetCities"
                ServicePath="WebService.asmx"
                Category="city" />           <%--WebService Method name--%>

Now you have done, run the page and see the results.................