Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Ajax Cascading Dropdownlist Sample with database using asp.net

Jan 12, 2011
Introduction:

Here I will explain how to use Ajax cascading dropdownlist with database using asp.net

Description:

In my previous article I explained
how to populate dropdown based on other dropdown using asp.net now I will explain how to use Ajax cascading dropdownlist in asp.net.
Here I already explained how to populate dropdown based on another dropdown but now why I am explaining about this Ajax cascading dropdownlist because if we use this Ajax cascading dropdownlist we can get the dropdown data without any postback operation and we don’t need to write extra code to disable dropdowns based on otherdropdown selection all the futures available with this Ajax cascading dropdown directly but here we need to write webservices to populate the dropdowns with data. 

Here I will explain with three dropdowns Country dropwdown, State dropdown, Region dropdown I need to populate states dropdown based on country dropdown and I need to populate region dropdown based on states dropdown for that what we have to do first design three tables in sql server with data like this 
Country Table
State Table
 Region Table 

After that add AjaxControlToolkit to your bin folder and design your aspx page like this
<%@ Register Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" tagPrefix="ajax" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptmanager1" runat="server"></asp:ScriptManager>
<div>
<table>
<tr>
<td>
Select Country:
</td>
<td>
<asp:DropDownList ID="ddlcountry" runat="server"></asp:DropDownList>
<ajax:CascadingDropDown ID="ccdCountry" runat="server" Category="Country" TargetControlID="ddlcountry" PromptText="Select Country" LoadingText="Loading Countries.." ServiceMethod="BindCountryDetails" ServicePath="CascadingDropdown.asmx">
</ajax:CascadingDropDown>
</td>
</tr>
<tr>
<td>
Select State:
</td>
<td>
<asp:DropDownList ID="ddlState" runat="server"></asp:DropDownList>
<ajax:CascadingDropDown ID="ccdState" runat="server" Category="State" ParentControlID="ddlcountry" TargetControlID="ddlState" PromptText="Select State" LoadingText="Loading States.." ServiceMethod="BindStateDetails" ServicePath="CascadingDropdown.asmx">
</ajax:CascadingDropDown>
</td>
</tr>
<tr>
<td>
Select Region:
</td>
<td>
<asp:DropDownList ID="ddlRegion" runat="server"></asp:DropDownList>
<ajax:CascadingDropDown ID="ccdRegion" runat="server" Category="Region" ParentControlID="ddlState" TargetControlID="ddlRegion" PromptText="Select Region" LoadingText="Loading Regions.." ServiceMethod="BindRegionDetails" ServicePath="CascadingDropdown.asmx">
</ajax:CascadingDropDown>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

After that add one new webservice page to your application and following namcespaces in your webservice code behind page


using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using AjaxControlToolkit;

Here we need to remember one point that is we need to write webmethods this format only and use exact parameters that should be same as whatever I mentioned in web method

[WebMethod]
public CascadingDropDownNameValue[] BindCountryDetails(string knownCategoryValues,string category)
In this web method we have a chance to change only method name return type also same CascadingDropDownNameValue[]

After completion of writing namespaces and write the following code in webservice page


/// <summary>
/// Summary description for CascadingDropdown
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class CascadingDropdown : System.Web.Services.WebService
{
//Database connection string
private static string strconnection = ConfigurationManager.AppSettings["ConnectionString"].ToString();
//database connection
SqlConnection concountry = new SqlConnection(strconnection);
public CascadingDropdown () {

//Uncomment the following line if using designed components
//InitializeComponent();
}
/// <summary>
/// WebMethod to Populate COuntry Dropdown
/// </summary>
[WebMethod]
public CascadingDropDownNameValue[] BindCountryDetails(string knownCategoryValues,string category)
{
concountry.Open();
SqlCommand cmdcountry = new SqlCommand("select * from CountryTable", concountry);
cmdcountry.ExecuteNonQuery();
SqlDataAdapter dacountry = new SqlDataAdapter(cmdcountry);
DataSet dscountry = new DataSet();
dacountry.Fill(dscountry);
concountry.Close();
//create list and add items in it by looping through dataset table
List<CascadingDropDownNameValue> countrydetails = new List<CascadingDropDownNameValue>();
foreach(DataRow dtrow in dscountry.Tables[0].Rows)
{
string CountryID = dtrow["CountryID"].ToString();
string CountryName = dtrow["CountryName"].ToString();
countrydetails.Add(new CascadingDropDownNameValue(CountryName, CountryID));
}
return countrydetails.ToArray();
}
/// <summary>
/// WebMethod to Populate State Dropdown
/// </summary>
[WebMethod]
public CascadingDropDownNameValue[] BindStateDetails(string knownCategoryValues,string category)
{
int countryID;
//This method will return a StringDictionary containing the name/value pairs of the currently selected values
StringDictionary countrydetails =AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
countryID = Convert.ToInt32(countrydetails["Country"]);
concountry.Open();
SqlCommand cmdstate = new SqlCommand("select * from StateTable where CountryID=@CountryID", concountry);
cmdstate.Parameters.AddWithValue("@CountryID", countryID);
cmdstate.ExecuteNonQuery();
SqlDataAdapter dastate = new SqlDataAdapter(cmdstate);
DataSet dsstate = new DataSet();
dastate.Fill(dsstate);
concountry.Close();
//create list and add items in it by looping through dataset table
List<CascadingDropDownNameValue> statedetails = new List<CascadingDropDownNameValue>();
foreach (DataRow dtrow in dsstate.Tables[0].Rows)
{
string StateID = dtrow["StateID"].ToString();
string StateName = dtrow["StateName"].ToString();
statedetails.Add(new CascadingDropDownNameValue(StateName, StateID));
}
return statedetails.ToArray();
}
/// <summary>
/// WebMethod to Populate Region Dropdown
/// </summary>
[WebMethod]
public CascadingDropDownNameValue[] BindRegionDetails(string knownCategoryValues, string category)
{
int stateID;
//This method will return a StringDictionary containing the name/value pairs of the currently selected values
StringDictionary statedetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
stateID = Convert.ToInt32(statedetails["State"]);
concountry.Open();
SqlCommand cmdregion = new SqlCommand("select * from RegionTable where StateID=@StateID", concountry);
cmdregion.Parameters.AddWithValue("@StateID", stateID);
cmdregion.ExecuteNonQuery();
SqlDataAdapter daregion = new SqlDataAdapter(cmdregion);
DataSet dsregion = new DataSet();
daregion.Fill(dsregion);
concountry.Close();
//create list and add items in it by looping through dataset table
List<CascadingDropDownNameValue> regiondetails = new List<CascadingDropDownNameValue>();
foreach (DataRow dtrow in dsregion.Tables[0].Rows)
{
string RegionID = dtrow["RegionID"].ToString();
string RegionName = dtrow["RegionName"].ToString();
regiondetails.Add(new CascadingDropDownNameValue(RegionName, RegionID));
}
return regiondetails.ToArray();
}
}

Demo


Download sample code attached
 

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

130 comments :

SUDHAKAR said...

//Database connection string
private static string strconnection = ConfigurationManager.AppSettings["ConnectionString"].ToString();

the above connection string should be something like this to execute the project.
private static string strconnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

Suresh Dasari said...

hi sudhakar here i written my connection string in appsettings that's why i have written

private static string strconnection = ConfigurationManager.AppSettings["ConnectionString"].ToString();to bring my connection file from appsettings.

if we write connection string in Configuration section we need to write like this
private static string strconnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

Both the ways are correct it's not a problem

SUDHAKAR said...

Ohh ic.. Anyways,, you did a great job. thanks for everything.

Suresh Dasari said...

Thanks Sudhakar keep visting.......

Bhaskar said...

Drop Down lists are showing empty..
but when i invoke the web service values show up on my screen..
what do i do?? :(

Suresh Dasari said...

hi bhaskar have you bind the dropdowns correctly with webservice please check your code and try it will work for you

Bhaskar said...

I have bound it like you said.. but the drop down lists are coming up empty..

Bhaskar said...

Code for the asmx file with the first web method which takes data from 'multiplex' table & displays it in the first drop down list::
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Configuration;
using AjaxControlToolkit;

///
/// Summary description for CascadingDropdown
///
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class CascadingDropdown : System.Web.Services.WebService {
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["cityguideConnectionString"].ConnectionString);

public CascadingDropdown () {

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

[WebMethod]
public CascadingDropDownNameValue[] BindMultiplexDetails(string knownCategoryValues, string category)
{
conn.Open();
SqlCommand cmdmultiplex = new SqlCommand("select * from dbo.multiplex", conn);
cmdmultiplex.ExecuteNonQuery();
SqlDataAdapter damultiplex = new SqlDataAdapter(cmdmultiplex);
DataSet dsmultiplex = new DataSet();
damultiplex.Fill(dsmultiplex);
List multiplexdetails = new List();
foreach (DataRow dtrow in dsmultiplex.Tables[0].Rows)
{
string multiplexid = dtrow["multiplexid"].ToString();
string multiplexname = dtrow["multiplex_name"].ToString();
multiplexdetails.Add(new CascadingDropDownNameValue(multiplexid, multiplexname));
}
return multiplexdetails.ToArray();
}

}

Suresh Dasari said...

hi bhaskar download the attached code and try it's working fine may be your missing some code steps in your application during binding the dropdown values

Bhaskar said...

i downloaded your sample & ran it..
The dropdown lists are showing empty.. it is showing 'Select Country' but it is showing '[Method Error 500]'..

Suresh Dasari said...

hi bhaskar,
i check the code once again it's working fine that Method Error 500 will occur because of missing below line in your webservice page
Add this line in webservice's code behind
[System.Web.Script.Services.ScriptService()]
it will fix the error some times this error occurs even if there is any error in your sql statements or webservice code, you need to check them as well

Cats said...

Hi, I checked all the coding and I still have the "Method Error 500". Is there anyway you can tell me what did I do wrong? Thanks

Suresh Dasari said...

@Bhaskar...

i attached updated Ajax Cascading sample now it's working perfect you download the code and try it will work for you

Suresh Dasari said...

@Cats.....

Sometimes method 500 error occur because of Ajax dll version problem . i updated Ajax dll and attached sample with latest modifications download code and try it will work

Subhash Jakhar said...

Dear Suresh,
in the dropdown show [method error 500] Plz Give me solution how i solve this.

Thank You

Suresh Dasari said...

hi subhash,
check all of my comments in that i mentioned all possibilities to solve that method error 500 still if you get error try to debug whether your able to debug webservice method or not

Subhash Jakhar said...

hi

downloaded code work properly but code That i managed that still showing [method error 500].
plz give some IDEA.

Thank You

swaths said...

Sir, Such A Valuable Code. I'm Learning Now Dotnet.Give me ur Suggestion How to do practice.

Suresh Dasari said...

Hi Swaths,
Everybody will ask same question here i written many articles you should take each article and do practice with those articles that is enough you will get good idea on .NET

Indian Patriotic said...

Hi,

I've downloaded u r code but got [WebMethod error 500]

Suresh Dasari said...

hi patriotic,
i checked it's working fine please check above comments to solve your problem and debug and check whether your able to get details from database or not

Anonymous said...

Hi,

I am using 2 dropdowns. One for Selecting Facility and other for Providers.
I did the same code as you mentioned.

I am getting an error,

foreach (DataRow dtrow in dsProviderList.Tables[0].Rows)
{
string ProviderID = dtrow["ProviderID"].ToString();
string ProviderName = dtrow["Providers"].ToString();
Providerdetails.Add(new CascadingDropDownNameValue(ProviderName, ProviderID));
}


error - Column 'ProviderID' does not belong to table Table.

Suresh Dasari said...

hi,
Please check your datatable contains ProviderID and Providers or not i think this error because your table doesnot contains those columns. please check it once

Anonymous said...

I got the error working
error - Column 'ProviderID' does not belong to table Table.

In the Provider table I was just selecting ProviderName alone.
Now I select ProviderID too...error solved.


Thanks for giving this artical really in understandable way...

Anonymous said...

Hi Suresh,

Now I have another issue.

I have Facility and Provider table.
Bases on FacilityID as input to Provider table we get values for both the drop down.
That works fine.

Now I need to get FacilityID and ProviderID of selected values in both dropdown list.

I need to pass those values in session variable to another page..

How do I do this????

Anonymous said...

hi, i cannot assign these dropdownlist values in to session variables. can anyone help?

Ravi said...

which version of visual studio in which you created this app?

Shaz said...

how to bind this dropdown in grid view in asp.net 3.5

Seamus said...

Great Article. I found this a far easier method than the one in the msdn tutorials. Thanks!

Anonymous said...

it is giving 404 error

Mishel said...

Thanxxxxxxxxx a lot man..

Anonymous said...

Hi sir

This is Rahul Dwivedi
your new follower.
I, m exporting my gridview into excel using your code but I,m getting error
this 'System.IO.StreamWriter' does not contain a constructor that takes 0 arguments

Anonymous said...

Hi,

can u plz provide "Database" also.
ur App_Data is blank

zalak said...

i want to get selected value of city and store selected city in database table so how can i do in this code

zalak said...

urgent reply plz

zalak said...

i want to get selected value of city at run time and store selected city name into database table

Ratul Paul said...

Hi, your post is very much helpful for me as it explains how to bind cascading dropdown from 3 different tables. Now I want to preselect values to the dropdowns from database(like if I use this example to a registration page, when a registered user tries to edit his/her profile the country, state and city must be preselected as they select of the time they registered.) Can you please explain how to do this? Thanx in advance, it urgent for me...

Anonymous said...

excellent

Abdul Rahman said...

When i using the ajax toolkit control, it showing the following error:
"Unknown server tag 'ajax:CascadingDropDown'."

Anonymous said...

hi sir iused ur code for practice but iam getting this error
'WebMethod' could not be found (are you missing a using directive or an assembly
pls sugggest me...

Suresh Dasari said...

@Shaz..
check this post to bind cascading dropdowns in gridview
http://www.aspdotnet-suresh.com/2011/11/how-to-implement-cascading-dropdownlist.html

Suresh Dasari said...

@Abdul Rahman..
That problem because of you didn't added ajaxcontroltoolkit dll to your application because of that it's not identifying ajax control toolkit. if you want to know how to install Ajax control toolkit check this post
http://www.aspdotnet-suresh.com/2011/11/how-to-install-ajax-control-toolkit-in.html

Suresh Dasari said...

@40 Comment
i think that WebMethod error because of missing Webmethod attribute in Webservice. Please read the post clearly and try it will work for you

Suresh Dasari said...

@Ratul Paul..
check this post to implemente cascading dropdown with preselected values
http://www.aspdotnet-suresh.com/2010/10/how-to-populate-dropdown-based-on-other.html

bhawana said...

thank u sir.....ur website help me a lot...

srilatha said...

Iam using asp.net2.0 application .I want to implement ajax controls on it. i got the dll included.but when i add an ajax control and run the application i get an error message "sys is undefined".can you please help me to make necessary changes in the web.config .Urgent requirement please???

Suresh Dasari said...

@srilatha..
you need to install correct version of dll based on your version check this post to install ajax control toolkit http://www.aspdotnet-suresh.com/2011/11/how-to-install-ajax-control-toolkit-in.html

srilatha said...

I am using Microsoft Visual WebDeveloper 2010 and the framework is 2.0.Can you please send me the correct dll for it.

thanks in advance

srilatha said...

Hi I have resolved my issue by adding the below code to my web.config file.

srilatha said...

But I have a new issue now.On the Country dropdown list I get [method error 500] I used exactly the same code as you provided

SOURAV said...

hi ...

i want to get the selected value from the cascading dropdownlist in a text box....is it possible to do it?????

plz help...

thanx :)

Anonymous said...

Hi Suresh

After writeing above code i am getting below error can you please guide me how to remove that error....
Error 1 'cascading.BindCountryDetails(string, string)': not all code paths return a value

José M. Vargas H. said...

How I can use Cascading DropDownList in a form?
Thank you very much.

José M. Vargas H. said...

Cascading DropDownList few objects on a form I can use?
Thank you very much.

Anonymous said...

how can i retrieve data in dropdownlist from database sql server 2008 in asp.net 3.5 with c#.
like country,state,district.

Anonymous said...

how can i retrieve data in dropdownlist from database sql server 2008 in asp.net 3.5 with c#.
like country,state,district.

aankur gupta (alld&sln)

Suresh Dasari said...

Check this post for dropdownlist from database like country state and district

http://www.aspdotnet-suresh.com/2010/10/how-to-populate-dropdown-based-on-other.html

Sanjeev Patel said...

Thanks for your code, in other examples from world, I always get ERROR 500
Now Its working
Thanks BRO

hemalisachdev said...

Hi frnds pls help me i m getting same error Method Error 500, i had fullfill all requirements and also given [System.Web.Script.Services.ScriptService()].
Bt still its nt working. Pls pls help me...
Thanx in advance.

Anonymous said...

very use this demo

Nitesh Agarwal said...

Hi Every body ,
I am Nitesh Agarwal.I have solved this Problem
of method error 500

Midhat said...

Its give the Method error 500 when I implement it with .net Framework 4.0.I have already add reference ajax toolkit4.0 in my bin folder

Suresh Dasari said...

@Midhat...
To sovle Method error 500 Please check this post http://www.aspdotnet-suresh.com/2011/12/method-error-50012031-in-ajax.html

Lion Tunnel - Welcome To All said...

Hi
Select mode working properly.but how to select default value. for example India->TamilNadu
->Channai

Lion Tunnel - Welcome To All said...

please urgent help me.

Anonymous said...

Hello sir,

Still am getting method 500 error.

jswidorski said...

Why do you have to reference the

StringDictionary countrydetails =AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
countryID = Convert.ToInt32(countrydetails["Country"]);

should the category be passed through to the webservice? Maybe someone can explain more to me

Anonymous said...

can u develop the attendance register form for employees..

Anonymous said...

Sir, i have used above sample in my site but getting results which are not desirable as only sql data base IDs as Railway=1, Division=1 or after some changes Railway=1:::CR:::, Division=1:::BSL:::.
Full details are attached at

http://stackoverflow.com/questions/10464713/how-to-use-cascade-dropdown-list-for-inserting-data

Sir, please help for rectifing the problem. my requirement is Railway=CR, Division=BSL

Anonymous said...

Rakesh:

Hi Suresh,
This site Helped Me A lot in my Projects..
I tried the same example, data is well displaying in dropdown Countries But when i select otem from dropdown the related items of that 1st selected Dropdown is not displaying in 2nd Dropdown... it is not activating....

Can u help me Out

Rakesh Dontha said...

public class DropdownWebService : System.Web.Services.WebService
{

[WebMethod]
public CascadingDropDownNameValue[] BindCountrydropdown(string knownCategoryValues, string category)
{
SqlConnection concountry = new SqlConnection(@"Data Source=XXXXX; User ID=rakesh;Password=;Initial Catalog=XXXX;");
concountry.Open();
SqlCommand cmdcountry = new SqlCommand("select * from DeptCode", concountry);
SqlDataAdapter dacountry = new SqlDataAdapter(cmdcountry);
cmdcountry.ExecuteNonQuery();
DataSet dscountry = new DataSet();
dacountry.Fill(dscountry);
concountry.Close();
List countrydetails = new List();
foreach (DataRow dtrow in dscountry.Tables[0].Rows)
{
string CountryID = dtrow["DeptID"].ToString();
string CountryName = dtrow["DeptCode"].ToString();
countrydetails.Add(new CascadingDropDownNameValue(CountryName, CountryID));
}
return countrydetails.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] BindStatedropdown(string knownCategoryValues, string category)
{
int CountryID;
StringDictionary countrydetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
CountryID = Convert.ToInt32(countrydetails["DeptCode"]);
SqlConnection constate = new SqlConnection(@"Data Source=XXXX; User ID=rakesh;Password=;Initial Catalog=XXXX;");
constate.Open();
SqlCommand cmdstate = new SqlCommand("select * from FileIndex where DeptID=@DeptID", constate);
cmdstate.Parameters.AddWithValue("@DeptID", CountryID);
cmdstate.ExecuteNonQuery();
SqlDataAdapter dastate = new SqlDataAdapter(cmdstate);
DataSet dsstate = new DataSet();
dastate.Fill(dsstate);
constate.Close();
List statedetails = new List();
foreach (DataRow dtstaterow in dsstate.Tables[0].Rows)
{
string stateID = dtstaterow["FileIndexID"].ToString();
string statename = dtstaterow["FileIndex"].ToString();
statedetails.Add(new CascadingDropDownNameValue(statename, stateID));
}
return statedetails.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] BindRegiondropdown(string knownCategoryValues, string category)
{
int stateID;
StringDictionary statedetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
stateID = Convert.ToInt32(statedetails["FileIndex"]);
SqlConnection conregion = new SqlConnection(@"Data Source=XXXX; User ID=XX;Password=;Initial Catalog=XXX;");
conregion.Open();
SqlCommand cmdregion = new SqlCommand("Select * from SubFileIndex where FileIndexID=@FileIndexID", conregion);
cmdregion.Parameters.AddWithValue("@FileIndexID", stateID);
cmdregion.ExecuteNonQuery();
SqlDataAdapter daregion = new SqlDataAdapter(cmdregion);
DataSet dsregion = new DataSet();
daregion.Fill(dsregion);
conregion.Close();
List regiondetails = new List();
foreach (DataRow dtregionrow in dsregion.Tables[0].Rows)
{
string regionID = dtregionrow["SubID"].ToString();
string regionname = dtregionrow["SubFileIndex"].ToString();
regiondetails.Add(new CascadingDropDownNameValue(regionname, regionID));

}
return regiondetails.ToArray();
}
}


This is my code....

I Want Output like

Dropdownlist1: 1,2,3,4,5,6,7....
DropdownList2:1.1,1.2,1.3,...(If we select 1)
DropDowList3:1.1.1,1.1.2,....(If We Select 1.1)
Please help Me out..

Anonymous said...

i also got same 5000 error but when i checked it ... i found the code downloaded has webmethod name BindCountrydropdown .. and according the tutorial it is mentioned that it should be ServiceMethod="BindCountrydetials" so now you have to chage it to ServiceMethod="Bindcountrydropdown"
do it same for sate , region

problem solved

Anonymous said...

i also got same 5000 error but when i checked it ... i found the code downloaded has webmethod name BindCountrydropdown .. and according the tutorial it is mentioned that it should be ServiceMethod="BindCountrydetials" so now you have to chage it to ServiceMethod="Bindcountrydropdown"
do it same for sate , region

problem solved

Basker Ganesan said...

@suresh
Compiler Error Message: CS0029: Cannot implicitly convert type 'AjaxControlToolkit.CascadingDropDownNameValue[]' to 'AjaxControlToolkit.CascadingDropDownNameValue'.
i am getting this error.
how to solve this.

DEEPAK GARG said...

i also got same 5000 error but when i checked it ... i found the code downloaded has webmethod name BindCountrydropdown .. and according the tutorial it is mentioned that it should be ServiceMethod="BindCountrydetials" so now you have to chage it to ServiceMethod="Bindcountrydropdown"
do it same for sate , region

problem solved

Rakesh Dontha said...
This comment has been removed by the author.
Rakesh Dontha said...

Hi Deepak,Thanks For ur reply....
I tried what u said, but its getting Error 5000, may i know the how to solve this error...
Its very urgent...

PURNA MAGUM said...

hai suresh,

good work... Thanks for posting this

Anonymous said...

hi suresh i am dnyaneshwar i am trying the same example but i got an error 'Method error 500'
please help

arr said...

Hi Suresh,

This code is working perfectly on local server. When i host this, dropdowns says {method error -404]. I couldn't find a good solution for this in google. What could be the reason for this?

Regards,
Aruna

Anonymous said...

who all got error 500...I think you all made the tables in database with the name country table, state table, region table. If so, while making the functions, in the web service, for the sql query, you have to put select * from [country table]. The table name should be in brackets.

Anonymous said...

We don't need any parameters for BindCountryDetails function in the webservice. In the code given here, the function BindCountryDetais is given parameters and that may be the reason why some are getting error 500

Anonymous said...

Thanks Brother.. you are making developers life easy ...

Anonymous said...

Hi suresh

how to get cascading dropdownlist selected indexchange items into listbox

Anonymous said...

Thanx Bro.
Good one

Anonymous said...

Hai suresh
many of the devolpers are faceing issue about method 500 error in above program please uncomment the cmd.executenonquery() of state method and region method please check once below program
[WebMethod]
public CascadingDropDownNameValue[] BindStateDetails(
string knownCategoryValues,
string category)
{
int CountryId;
StringDictionary countrydetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
CountryId = Convert.ToInt32(countrydetails["Country"]);
SqlCommand cmd = new SqlCommand("select * from State Where Countryid= @Countryid", con);
cmd.Parameters.AddWithValue("@Countryid", CountryId);
//cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
List statedetails = new List();
foreach (DataRow dtrow in ds.Tables[0].Rows)
{
string StateId = dtrow["Stateid"].ToString();
string stateName = dtrow["Statename"].ToString();
statedetails.Add(new CascadingDropDownNameValue(stateName, StateId));

}
return statedetails.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] BindRegionDetails(
string knownCategoryValues,
string category)
{
int StateId;
StringDictionary statedetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
StateId = Convert.ToInt32(statedetails["State"]);
SqlCommand cmd = new SqlCommand("select * from Region where Stateid=@Stateid", con);
cmd.Parameters.AddWithValue("@Stateid", StateId);
//cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
List regiondetails = new List();
foreach (DataRow dtrow in ds.Tables[0].Rows)
{
string RegionId = dtrow["Regionid"].ToString();
string Regionname = dtrow["Regionname"].ToString();
regiondetails.Add(new CascadingDropDownNameValue(Regionname, RegionId));
}
return regiondetails.ToArray();
}
}


}
enjoy above code.....

sankar reddy said...

hi

i need some help from you.

the cascading dropdownlist is working fine in country ddl.while state ddl was not loading what will be the problem

Anonymous said...

hai sankar ,
please uncomment the cmd.executenonquery() method
both state() method and Region() method...
let try .....once

rakesh said...

hai sankar ,

please see the code comment no-86

sankar reddy said...

hi,

this is my coding country was loading fine stste table was loading please clear the problem


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

[WebMethod]
public CascadingDropDownNameValue[] BindCountrydropdown(string knownCategoryValues, string category)
{
SqlConnection concountry = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
concountry.Open();
SqlCommand cmdcountry = new SqlCommand("select CountryID,CountryName from tblCountry", concountry);
SqlDataAdapter dacountry = new SqlDataAdapter(cmdcountry);
cmdcountry.ExecuteNonQuery();
DataSet dscountry = new DataSet();
dacountry.Fill(dscountry);
concountry.Close();
List countrydetails = new List();
foreach(DataRow dtrow in dscountry.Tables[0].Rows)
{
string CountryID = dtrow["CountryID"].ToString();
string CountryName = dtrow["CountryName"].ToString();
countrydetails.Add(new CascadingDropDownNameValue(CountryName,CountryID));
}
return countrydetails.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] BindStatedropdown(string knownCategoryValues, string category)
{
int CountryID;
StringDictionary countrydetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
CountryID = Convert.ToInt32(countrydetails["tblCountry"]);
SqlConnection constate = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
constate.Open();
SqlCommand cmdstate = new SqlCommand("select StateID,StateName from tblState where CountryID=@CountryID", constate);
cmdstate.Parameters.AddWithValue("@CountryID", CountryID);
//cmdstate.ExecuteNonQuery();
SqlDataAdapter dastate = new SqlDataAdapter(cmdstate);
DataSet dsstate = new DataSet();
dastate.Fill(dsstate);
constate.Close();
List statedetails = new List();
foreach (DataRow dtstaterow in dsstate.Tables[0].Rows)
{
string stateID = dtstaterow["StateID"].ToString();
string statename = dtstaterow["StateName"].ToString();
statedetails.Add(new CascadingDropDownNameValue(statename, stateID));
}
return statedetails.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] BindRegiondropdown(string knownCategoryValues, string category)
{
int stateID;
StringDictionary statedetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
stateID = Convert.ToInt32(statedetails["tblState"]);
SqlConnection conregion = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
conregion.Open();
SqlCommand cmdregion = new SqlCommand("Select * from tblCity where StateID=@StateID", conregion);
cmdregion.Parameters.AddWithValue("@StateID", stateID);
//cmdregion.ExecuteNonQuery();
SqlDataAdapter daregion = new SqlDataAdapter(cmdregion);
DataSet dsregion = new DataSet();
daregion.Fill(dsregion);
conregion.Close();
List regiondetails = new List();
foreach (DataRow dtregionrow in dsregion.Tables[0].Rows)
{
string regionID = dtregionrow["ID"].ToString();
string regionname = dtregionrow["Name"].ToString();
regiondetails.Add(new CascadingDropDownNameValue(regionname,regionID));

}
return regiondetails.ToArray();
}

Steve Cone said...

This is awesome! However is there a way to use this code in a formview "edit template" and somehow bind the data?

Anonymous said...

hi

shambhu sharan said...

There is a big problem that validation is not working with ajax cascading dropdown . i request to you please give me solution.

N.Shivesh said...

great tutorial suresh...

thankx

ramesh said...

hello sir, on my O/P it displaying all dropdownlist in that iam getting [method error 500] in 3 drop downlist.....

ramesh said...

k i got sir

Anonymous said...

Iam Getting Error As:[Method Error 500] ...Anyone give me the Solution...Manu here

Sanjeet Kumar said...

Hi I am Sanjeet Albela........

How to learn Web Service ????

Please tell me Process?????

Suresh sir..

sunil.kumar said...

Sir, I am trying to use this example in project under Formview Insert Item template. List populated well but after pressing insert button. No value passed to Database i.e. Databse is remains blank. please help.

navya said...

huge ful tutorial very nice.........

Hussain Shariff said...

Is web service method compulsory? Can we use the cascadingdropdown without Web Service?

Anonymous said...

way to go bro!
I was searching for this thing for quite a time and you covered it all well.

Thanx

sunil said...

Hi!

Am working on building master pages. In that there is a drop-down control were the values are shown for selection. If any value is not available ( then a link is given beside it, once we click that it will open a popup box with a page to insert the new item or value )....... one the new value is inserted into database. My requirement is that new value must be visible in the drop-down box as a default by refreshing. How?

Need help in that....

With Regards
Suneel

Vithyasamanavan said...

hi suresh ... please give the link for updated country db...

THIRU MUDI said...

Hi suresh sir!
why was use in ajax control

aparna said...

Thank u Suresh very nice exp..

Anonymous said...

Can't we paste <asp:Dropdownlist directly in the Update Panel?

Anonymous said...

Hello Sir,
I am not the exception unlike other followers..
I have also got:method error 500..
I have also gone through your troubleshooting tutorial.. still getting same error..

please help..

priyank patel said...

hi sir i am priyank patel.. i am student of tops technology .. i use yr example works fine but when i insert data by this dropdown to table its error that is invalid postback error ..plz solved it ..i tried for 3 days but not solved

geetha samynathan said...

Hi suresh,
Using your post only i learned many things. Each and every post is very helpful to learn all control without reading book.

i tried the Same code but, it shows the error in webservice

public CascadingDropDownNameValue[] BindCountryDetails(string knownCategoryValues, string category)
{
the type or namespace name 'CascadingDropDownNameValue' could not be found.

Please anyone help to add webservice in asp.net application step by step.it's Very Urgent.

Vinod said...

you are great sir

Anonymous said...

Hi,

When Form is opened, Country dropdown list is properly loaded with a country name list but State and Region dropdown were disabled. Any ideas why they are disabled? Thanks.

Anonymous said...

Hi,
I am Saroj ,I got same error like [Method error 500].But it solved,
1.First check the connection string in Webconfig file,
2.Create Tables in perfect naming like suresh)
3.Give the table name Country not Country Table.
4.First fill the tables then try to retrive..

I think it will be help u for solving the [Methord error 500]

Thanks suresh to help us..

regards
saroj

Anonymous said...

Hi suresh really very good ,but i want more exception from your end you know know we r using 4.0 or 4.5 version and you didn't mention any thing in both version if you updated any thing (Just like new interview q ans Ans,wcf in 4.0 or 4.5 etc) Thanks Arjun walmiki

Anonymous said...

Hi suresh really very good.Code is working but one problem is if value fetch in drop down(Like 1000 or more )its gives error 500.Please help

Anonymous said...

Hi Suresh I want to know other than this topic...
I have created a software which contain a .mdf file but the connection String which i am using is of my system file location. so , i am unable to run the software in another PC. can u suggest a way so that it can run in any PC.I have used viual studio 2010 to develop the software..

Harshit said...

CountryID = Convert.ToInt32(countrydetails["Country"]);
what is Country here??

Mahi ummaneni said...

hi this is mahesh,
i am unable to get values to dropdownlist.
i am getting error like method error 1230,like thet am getting can u please chaeck it once.

Anonymous said...

How to fill Drop Down list i am blank drop down list

Anonymous said...

hi.......sir.this error occure during running

Could not load type 'System.Web.UI.ScriptReferenceBase' from assembly 'System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

Anonymous said...

Thanks Brother.. you are awesome

XYZ said...

Hello Sir!!

Thanks a lot for the gr8 help. It works but I am facing a problem in filtering the data in my web method I want to filter the data. If I select a particular state it should show only districts in that particular state but it doesn't allow me to query on the dropdownlist in the web method. How to call the dropdownlist in the web method Please help..

Anil Kumar said...

it is very helpful

phani said...

Hiii, I have a problem with the Cascading drop down.
Cascading drop down is getting refreshed infinetly. in Chrome and safari browser.
This issue is not appearing in IE and firefox. I have tried adding Microsoft ajax scripts in the script manager and added the browser compatability code but nothing worked for me. Please let me know if there is any solution regarding this issue.
My email id is phaniraj1987@gmail.com

chandan kumar said...

cn u plz post hw to bind dropdown in 3 tier using object...plz as soon as possible

RB said...

I extended your approach as follows:
DropDownList droplist = new DropDownList();
droplist.ID = "DropDownListOrderTask";
droplist.AutoPostBack = true;
item["OrderTask"].Controls.Add(droplist);

CascadingDropDown ccdOrderTask = new CascadingDropDown();
ccdOrderTask.ID = "ccdOrderTask";
ccdOrderTask.Category = "OrderTask";
ccdOrderTask.TargetControlID = "DropDownListOrderTask";
ccdOrderTask.PromptText = "Select Order Task";
ccdOrderTask.LoadingText = "Loading OrderTask";
ccdOrderTask.ServiceMethod = "BindOrderTask";
ccdOrderTask.ServicePath = "~/ajax/ajaxservice.asmx";

TextBox txt = (TextBox)item["TaskOwner"].Controls[0];
txt.Visible = false;
droplist = new DropDownList();
droplist.ID = "DropDownListTaskOwner";
item["TaskOwner"].Controls.Add(droplist);
CascadingDropDown ccdTaskOwner = new CascadingDropDown();
ccdTaskOwner.ID = "ccdTaskOwner";
ccdTaskOwner.Category = "TaskOwner";
ccdTaskOwner.ParentControlID = "DropDownListOrderTask";
ccdTaskOwner.TargetControlID = "DropDownListTaskOwner";
ccdTaskOwner.PromptText = "Select Task Owner";
ccdTaskOwner.LoadingText = "Loading Task Owner";
ccdTaskOwner.ServiceMethod = "BindTaskOwner";
ccdTaskOwner.ServicePath = "~/ajax/ajaxservice.asmxajaxservice.asmx";

But the dropdown is empty!

P H Mani said...

Hello Admin. Im new .Net ... tried ur code in my application I got result also...But I have problem here.....I have 4 Cascade Dropdowns and Button control.Here, without giving Selcting the dropdowns directly fire button control come to Button method...But after all the dropdowns ,i fire the button....but the control doesnt come to Button method ...I dont know what is the Reason please help me out

P H Mani said...

Hello Admin. Im new .Net ... tried ur code in my application I got result also...But I have problem here.....I have 4 Cascade Dropdowns and Button control.Here, without giving Selcting the dropdowns directly fire button control come to Button method...But after Selecting all the dropdowns values Im trying to fire the button....but the control doesnt come to Button method ...I dont know what is the Reason please help me out

sumesh np said...

Hi Suresh,
Https is blocking Ajax Cascading Dropdownlist content in all browsers, How to solve this issue?

Sushil Gupta said...

hi...suresh Bro..
I have done all thing but if record is more than 200 then fire error [error 500] .Plesae help me as soon as possible at my Id: sushil7350@gmail.com

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.