Wednesday, February 29

Ajax Cascading Dropdownlist Sample with database using asp.net


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 id="Head1" 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 sameCascadingDropDownNameValue[]

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
 

Thanks Shibashish Mohanty

.

ShibashishMnty
shibashish mohanty