AJAX Cascading Dropdown Example using SQL Database

Updated on 19 Apr 2012,
Published on 05 Jun 2008

The AJAX Cascading Dropdown extender control can also be used with SQL Server Database to populate the target dropdown controls with data retrieved form the database using web service method. Here we will use the same example of Northwind database in which first drop will display the categories retrieved from the categories table of Northwind and on selected index event will call the web service method to populate the other dropdown control with the products that belong to the selected category.

AJAX Control Toolkit Examples:

You can see the live samples and examples of AJAX Control Toolkit from the following links:

In this sample example for AJAX cascading dropdown control to work with SQL Database we will see how the Category property plays an important role to retrieve the related results from the database tables.

HTML code for Cascading Dropdown Extender Control

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

<table border="0" cellpadding="2" cellspacing="0" width="500">
    <tr>
        <td width="100">
            <b>Select Category :</b></td>
        <td>
            <asp:DropDownList ID="drdCategory" runat="server">
            </asp:DropDownList>
            <ajaxToolkit:CascadingDropDown
            ID="CascadingDropDown1"
            runat="server"
            Category="category"
            TargetControlID="drdCategory"
            PromptText="[Select Category]"
            LoadingText="Loading categories..."
            ServicePath="cascadingdataservice.asmx"
            ServiceMethod="GetDropDownCategories">
            </ajaxToolkit:CascadingDropDown>
        </td>
    </tr>
    <tr>
        <td>
            <b>Select Product :</b></td>
        <td>
            <asp:DropDownList ID="drdProduct" runat="server" OnSelectedIndexChanged="drdProduct_SelectedIndexChanged" AutoPostBack="True">
            </asp:DropDownList>
            <ajaxToolkit:CascadingDropDown ID="CascadingDropDown2" runat="server"
            Category="product"
            TargetControlID="drdProduct"
            ParentControlID="drdCategory"
            PromptText="[Select Product]"
            LoadingText="Loading products..."
            ServicePath="cascadingdataservice.asmx"
            ServiceMethod="GetDropDownProducts">
            </ajaxToolkit:CascadingDropDown>
        </td>
    </tr>
    <tr>
        <td colspan="2">
             </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                    <asp:Label ID="Label1" runat="server" Font-Size="16px" ForeColor="Maroon" Style="padding: 5px;"></asp:Label>
                </ContentTemplate>
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="drdProduct" EventName="SelectedIndexChanged" />
                </Triggers>
            </asp:UpdatePanel>
        </td>
    </tr>
</table>

When ParentControlID is passed to the Cascading Dropdown extender it sends the value of the selected item of parent dropdown control along with its key name defined in the Category Property of Parent dropdown control. In the sample code you will see that categoryID of the selected item of categories dropdown (Parent Dropdown control) is sent to the web method when any categoryName is selected. It passed the combination of Category Property value and selected item value of Parent Dropdown control as:

category:3
or
category:5

In the above values category is the key name used in the Category property of first dropdown control of the Cascading Dropdown sample. Numeric value is the categoryID of the selected item. knownCategoryValues parameter of the web method provides the value for the selected item of Parent Dropdown control.

To use the above value you can declare a variable of type StringDictionary and parse it using:

StringDictionary categoryValues = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

StringDictionary class belongs to the Specialized namespace of System.Collections

List<> type Generic collection can be used to accumulate the results retrieved using SqlDataAdapter:

List<AjaxControlToolkit.CascadingDropDownNameValue> cascadingValues = new List<AjaxControlToolkit.CascadingDropDownNameValue>();

In the web method used for web service of cascading dropdown extender control You can use the different names for the web methods but you have to use the same name and datatype of the web method parameters and return type as used in the provided web service sample. E.g.:

public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownCategories(string knownCategoryValues, string category)

You have to set the EnableEventValition="false" in the <% @Page %> header section of ASP.Net web page to enable the Asynchronous postback triggers of UpdatePanel.

C# Page Code
protected void drdProduct_SelectedIndexChanged(object sender, EventArgs e)
{
    Label1.BackColor = System.Drawing.Color.FromName("#FFFF80");
    Label1.Text = string.Format("You selected <b>{0}</b> from <b>{1}</b> category.", drdProduct.SelectedItem.Text, drdCategory.SelectedItem.Text);
}
C# WebService Code
string conString = System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ToString();

public CascadingDataService () {

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

[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownCategories(string knownCategoryValues, string category)
{
    SqlConnection sqlConn = new SqlConnection(conString);
    sqlConn.Open();
    SqlCommand sqlSelect = new SqlCommand("SELECT * FROM Categories", sqlConn);
    sqlSelect.CommandType = System.Data.CommandType.Text;
    SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlSelect);
    DataSet myDataset = new DataSet();
    sqlAdapter.Fill(myDataset);
    sqlConn.Close();

    List<AjaxControlToolkit.CascadingDropDownNameValue> cascadingValues = new List<AjaxControlToolkit.CascadingDropDownNameValue>();

    foreach (DataRow dRow in myDataset.Tables[0].Rows)
    {
        string categoryID = dRow["categoryID"].ToString();
        string categoryName = dRow["categoryName"].ToString();
        cascadingValues.Add(new AjaxControlToolkit.CascadingDropDownNameValue(categoryName,categoryID));
    }

    return cascadingValues.ToArray();
}

[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownProducts(string knownCategoryValues, string category)
{
    int categoryID;

    StringDictionary categoryValues = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
    
    categoryID = Convert.ToInt32(categoryValues["category"]);

    SqlConnection sqlConn = new SqlConnection(conString);
    sqlConn.Open();
    SqlCommand sqlSelect = new SqlCommand("SELECT * FROM Products where categoryID = @categoryID", sqlConn);
    sqlSelect.CommandType = System.Data.CommandType.Text;
    sqlSelect.Parameters.Add("@categoryID", SqlDbType.Int).Value = categoryID;
    SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlSelect);
    DataSet myDataset = new DataSet();
    sqlAdapter.Fill(myDataset);
    sqlConn.Close();

    List<AjaxControlToolkit.CascadingDropDownNameValue> cascadingValues = new List<AjaxControlToolkit.CascadingDropDownNameValue>();

    foreach (DataRow dRow in myDataset.Tables[0].Rows)
    {
        string productID = dRow["productID"].ToString();
        string productName = dRow["productName"].ToString();
        cascadingValues.Add(new AjaxControlToolkit.CascadingDropDownNameValue(productName, productID));
    }

    return cascadingValues.ToArray();
}

Output:

You can see the output of above discussed code from the following link:

AJAX CascadingDropdown Control SQL DataBinding

Continue to next tutorial: AJAX Cascading Dropdown Example using XML Data to learn how to bind the XML data to Cascading Dropdown control of AJAX toolkit.

19 Responses to "AJAX Cascading Dropdown Example using SQL Database"
ali bawi
hi
I need this sample
Prasenjit Basu
Hi,
I am getting error in the web service method as Method error 500. Below is the code for the both the i have already added the System.Web.Script.Services.ScriptService() in my web service please help as this is urgent:

[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownProducts(string knownCategoryValues, string category)
{
int categoryID;
StringDictionary categoryValues = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
string enqno = categoryValues["category"].ToString();
//categoryID = Convert.ToInt32(categoryValues["category"]);
SqlConnection sqlConn = new SqlConnection(conString);
sqlConn.Open();
SqlCommand sqlSelect = new SqlCommand("SELECT QuotationNo,QuotationDate FROM Cadillac_WFM_Quotation_Table where EnquiryNo = @enqno", sqlConn);
sqlSelect.CommandType = System.Data.CommandType.Text;
sqlSelect.Parameters.Add("@enqno", SqlDbType.VarChar, 50).Value = enqno;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlSelect);
DataSet myDataset = new DataSet();
sqlAdapter.Fill(myDataset);
sqlConn.Close();
List cascadingValues = new List();
foreach (DataRow dRow in myDataset.Tables[0].Rows)
{
string productID = dRow["QuotationNo"].ToString();
string productName = dRow["QuotationDate"].ToString();
cascadingValues.Add(new AjaxControlToolkit.CascadingDropDownNameValue(productName, productID));
}
return cascadingValues.ToArray();
}
Hasmukh Jain
hi thanks for such a wonderful article i have one problem. After performing all the steps defined by you, The selectedindexchanged event does not fire of drdproduct please help me to solve this problem.
anamika
hi ur article is very nice.i m doing my web service coding in page that is created through asp controls smart tag option"add auto complete page method" as described in my Wrox book.my code runs successfully but when i select 2nd dropdown list i am getting "method error 500".while debugging,i see that stringdictionary variable is not getting the value.i am also getting message of disassembly.i mnot understanding whats happening here.plz help.if u say i will send u my code.
Nguyen Nam
Can u send me a link to download Code and database for this sample Thank you very much!
Ezineasp.net
Hi Nguyen Nam

The code is already available in this tutorial and we have used the Northwind Sql database to run its sample. If you don't have the northwind database then you can download it here:

http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en
Alvaro
what i cant find yet is what everybody is probably looking for. A 3 level interdependent select lists where also the first list is populated from the DB and not hardcoded or static written, of course, using ajax and php
yasamadair
When I use this sample, I faced errors again and again. Finally, I realized on
cascadingValues.Add(new AjaxControlToolkit.CascadingDropDownNameValue(categoryName,categoryID));
lines of both methods, int values (categoryID etc. anyID) should be converted by toString(). Don't forget to add this converting!
nicky
After much hair pulling and searching all over the internet i stumbled on this article. It works for me thank you very much for posting!!!!
Manoj
...help ful for me...
please tell me how to fill multiple casecading dropdown on selection of a parrent cascading drop down

Thanks in Advance..
davidxie
hello

when the Form was submit,

how to get the selectedvalue from the DropDownList?

can I use Html.DropDownList instead of asp:DropDownList if yes ,how to do it ?
Mahesh
Hi, I have done the same thing as what was said above but the product dropdown was empty. please any one tell me what should I do. Thanks in advance. Mahesh
Sam
Hi, On page load none of my drop down is getting any values. I'm getting following value in my first drop down. [Method (500)] Please help
Kiran Shinde
i have tried the above code but i am too getting the same error as [Method (500)] in the drop-down list.
please help me out .
Ratul
Thank you for this great article. I want to download the sample, but the download link of this article redirects to the same page again ... why this is happened?
mahender
don't forgot -->
NicelyDone
Perfect, just what I was looking for. In reply to "i have tried the above code but i am too getting the same error as [Method (500)] in the drop-down list." Ensure you do not have any db connectivity issues, if you don't have the right db string connection specified, or the right table or field then you will get this error. To look at your http requests, open up Firebug using Firefox and look under Net --> XHR there you should see any error logs associated with the Get requests, etc...
Mathan
i need sample project for using cascading dropdownlist box.with full source code and form because i need to learn for my project
Gen
"You have to set the EnableEventValition="false" in the <% @Page %> header section of ASP.Net web page to enable the Asynchronous postback triggers of UpdatePanel." Did you mean EnableEventValidation="false" ?
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers