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 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
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. |
|||
|
|||
137 comments :
//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;
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
Ohh ic.. Anyways,, you did a great job. thanks for everything.
Thanks Sudhakar keep visting.......
Drop Down lists are showing empty..
but when i invoke the web service values show up on my screen..
what do i do?? :(
hi bhaskar have you bind the dropdowns correctly with webservice please check your code and try it will work for you
I have bound it like you said.. but the drop down lists are coming up empty..
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();
}
}
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
i downloaded your sample & ran it..
The dropdown lists are showing empty.. it is showing 'Select Country' but it is showing '[Method Error 500]'..
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
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
@Bhaskar...
i attached updated Ajax Cascading sample now it's working perfect you download the code and try it will work for you
@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
Dear Suresh,
in the dropdown show [method error 500] Plz Give me solution how i solve this.
Thank You
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
hi
downloaded code work properly but code That i managed that still showing [method error 500].
plz give some IDEA.
Thank You
Sir, Such A Valuable Code. I'm Learning Now Dotnet.Give me ur Suggestion How to do practice.
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
Hi,
I've downloaded u r code but got [WebMethod error 500]
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
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.
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
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...
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????
hi, i cannot assign these dropdownlist values in to session variables. can anyone help?
which version of visual studio in which you created this app?
how to bind this dropdown in grid view in asp.net 3.5
Great Article. I found this a far easier method than the one in the msdn tutorials. Thanks!
it is giving 404 error
Thanxxxxxxxxx a lot man..
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
Hi,
can u plz provide "Database" also.
ur App_Data is blank
i want to get selected value of city and store selected city in database table so how can i do in this code
urgent reply plz
i want to get selected value of city at run time and store selected city name into database table
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...
excellent
When i using the ajax toolkit control, it showing the following error:
"Unknown server tag 'ajax:CascadingDropDown'."
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...
@Shaz..
check this post to bind cascading dropdowns in gridview
http://www.aspdotnet-suresh.com/2011/11/how-to-implement-cascading-dropdownlist.html
@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
@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
@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
thank u sir.....ur website help me a lot...
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???
@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
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
Hi I have resolved my issue by adding the below code to my web.config file.
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
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 :)
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
How I can use Cascading DropDownList in a form?
Thank you very much.
Cascading DropDownList few objects on a form I can use?
Thank you very much.
how can i retrieve data in dropdownlist from database sql server 2008 in asp.net 3.5 with c#.
like country,state,district.
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)
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
Thanks for your code, in other examples from world, I always get ERROR 500
Now Its working
Thanks BRO
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.
very use this demo
Hi Every body ,
I am Nitesh Agarwal.I have solved this Problem
of method error 500
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
@Midhat...
To sovle Method error 500 Please check this post http://www.aspdotnet-suresh.com/2011/12/method-error-50012031-in-ajax.html
Hi
Select mode working properly.but how to select default value. for example India->TamilNadu
->Channai
please urgent help me.
Hello sir,
Still am getting method 500 error.
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
can u develop the attendance register form for employees..
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
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
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..
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
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
@suresh
Compiler Error Message: CS0029: Cannot implicitly convert type 'AjaxControlToolkit.CascadingDropDownNameValue[]' to 'AjaxControlToolkit.CascadingDropDownNameValue'.
i am getting this error.
how to solve this.
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
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...
hai suresh,
good work... Thanks for posting this
hi suresh i am dnyaneshwar i am trying the same example but i got an error 'Method error 500'
please help
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
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.
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
Thanks Brother.. you are making developers life easy ...
Hi suresh
how to get cascading dropdownlist selected indexchange items into listbox
Thanx Bro.
Good one
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.....
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
hai sankar ,
please uncomment the cmd.executenonquery() method
both state() method and Region() method...
let try .....once
hai sankar ,
please see the code comment no-86
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();
}
This is awesome! However is there a way to use this code in a formview "edit template" and somehow bind the data?
hi
There is a big problem that validation is not working with ajax cascading dropdown . i request to you please give me solution.
great tutorial suresh...
thankx
hello sir, on my O/P it displaying all dropdownlist in that iam getting [method error 500] in 3 drop downlist.....
k i got sir
Iam Getting Error As:[Method Error 500] ...Anyone give me the Solution...Manu here
Hi I am Sanjeet Albela........
How to learn Web Service ????
Please tell me Process?????
Suresh sir..
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.
huge ful tutorial very nice.........
Is web service method compulsory? Can we use the cascadingdropdown without Web Service?
way to go bro!
I was searching for this thing for quite a time and you covered it all well.
Thanx
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
hi suresh ... please give the link for updated country db...
Hi suresh sir!
why was use in ajax control
Thank u Suresh very nice exp..
Can't we paste <asp:Dropdownlist directly in the Update Panel?
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..
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
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.
you are great sir
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.
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
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
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
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..
CountryID = Convert.ToInt32(countrydetails["Country"]);
what is Country here??
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.
How to fill Drop Down list i am blank drop down list
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'.
Thanks Brother.. you are awesome
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..
it is very helpful
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
cn u plz post hw to bind dropdown in 3 tier using object...plz as soon as possible
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!
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
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
Hi Suresh,
Https is blocking Ajax Cascading Dropdownlist content in all browsers, How to solve this issue?
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
[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"].ConnectionString);
concountry.Open();
SqlCommand cmdcountry = new SqlCommand("select * from country_TB1", 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["country_id"].ToString();
string CountryName = dtrow["country_name"].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["country"]);
SqlConnection constate = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
constate.Open();
SqlCommand cmdstate = new SqlCommand("select * from state_TB1 where country_id=@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["state_id"].ToString();
string statename = dtstaterow["state_name"].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["state"]);
SqlConnection conregion = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
conregion.Open();
SqlCommand cmdregion = new SqlCommand("Select * from region_tb1 where state_id=@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["region_id"].ToString();
string regionname = dtregionrow["region_name"].ToString();
regiondetails.Add(new CascadingDropDownNameValue(regionname,regionID));
}
return regiondetails.ToArray();
}
}
above code is runable
Nice post dear.
it giving me metho error 500 on state drop down menu...
below is code please suggest.
[WebMethod]
public CascadingDropDownNameValue[] BindCountrydropdown(string knownCategoryValues, string category)
{
SqlConnection concountry = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
concountry.Open();
SqlCommand cmdcountry = new SqlCommand("select * from Country", 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["Country_Name"].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["Country"]);
SqlConnection constate = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
constate.Open();
SqlCommand cmdstate = new SqlCommand("select * from State 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["State_Name"].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["State"]);
SqlConnection conregion = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
conregion.Open();
SqlCommand cmdregion = new SqlCommand("Select * from city 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["cityID"].ToString();
string regionname = dtregionrow["city_Name"].ToString();
regiondetails.Add(new CascadingDropDownNameValue(regionname,regionID));
}
return regiondetails.ToArray();
}
please ignore above code it was
SqlConnection concountry = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
concountry.Open();
SqlCommand cmdcountry = new SqlCommand("SELECT countryid, country_name FROM country", 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["country_name"].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["country"]);
SqlConnection constate = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
constate.Open();
SqlCommand cmdstate = new SqlCommand("select stateid, state_name,countryid from state 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["state_name"].ToString();
statedetails.Add(new CascadingDropDownNameValue(statename, stateid));
}
return statedetails.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] BindcityDropdown(string knowcategoryvalues, string category)
{
int stateid;
StringDictionary statedetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knowcategoryvalues);
stateid = Convert.ToInt32(statedetails["state"]);
SqlConnection concity = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
concity.Open();
SqlCommand cmdcity = new SqlCommand("select cityid,city_name,stateid from city where stateid=@stateid", concity);
cmdcity.Parameters.AddWithValue("@state", stateid);
cmdcity.ExecuteNonQuery();
SqlDataAdapter dacity = new SqlDataAdapter(cmdcity);
DataSet dscity = new DataSet();
dacity.Fill(dscity);
concity.Close();
List citydetails = new List();
foreach (DataRow dtcityrow in dscity.Tables[0].Rows)
{
string cityid = dtcityrow["cityid"].ToString();
string cityname = dtcityrow["city_name"].ToString();
citydetails.Add(new CascadingDropDownNameValue(cityname, cityid));
}
return citydetails.ToArray();
}
i am getting the error there is no source code available for this location..plz help
sir i try all solution ..but still am getting empty drop-down list plzzzzzzz help m ....
i run only web services it give m correct output...but in web page dropdown list is empty
Note: Only a member of this blog may post a comment.