"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Using CascadingDropDown with a Database (C#)

by Christian Wenz

Download Code or Download PDF

The CascadingDropDown control in the AJAX Control Toolkit extends a DropDownList control so that changes in one DropDownList loads associated values in another DropDownList. In order for this to work, a special web service must be created.

Overview

The CascadingDropDown control in the AJAX Control Toolkit extends a DropDownList control so that changes in one DropDownList loads associated values in another DropDownList. (For instance, one list provides a list of US states, and the next list is then filled with major cities in that state.) In order for this to work, a special web service must be created.

Steps

First of all, a data source is required. This sample uses the AdventureWorks database and the Microsoft SQL Server 2005 Express Edition. The database is an optional part of a Visual Studio installation (including express edition) and is also available as a separate download under https://go.microsoft.com/fwlink/?LinkId=64064. The AdventureWorks database is part of the SQL Server 2005 Samples and Sample Databases (download at https://www.microsoft.com/downloads/details.aspx?FamilyID=e719ecf7-9f46-4312-af89-6ad8702e4e6e&DisplayLang=en). The easiest way to set the database up is to use the Microsoft SQL Server Management Studio Express (https://www.microsoft.com/downloads/details.aspx?FamilyID=c243a5ae-4bd1-4e3d-94b8-5a0f62bf7796&DisplayLang=en) and attach the AdventureWorks.mdf database file.

For this sample, we assume that the instance of the SQL Server 2005 Express Edition is called SQLEXPRESS and resides on the same machine as the web server; this is also the default setup. If your setup differs, you have to adapt the connection information for the database.

In order to activate the functionality of ASP.NET AJAX and the Control Toolkit, the ScriptManager control must be put anywhere on the page (but within the <form> element):

[!code-aspxMain]

   1:  <asp:ScriptManager ID="asm" runat="server" />

In the next step, two DropDownList controls are required. In this sample, we use the vendor and contact information from AdventureWorks, thus we create one list for the available vendors and one for the available contacts:

[!code-aspxMain]

   1:  <div>
   2:   Vendor: <asp:DropDownList ID="VendorsList" runat="server"/><br />
   3:   Contacts: <asp:DropDownList ID="ContactsList" runat="server"/><br />
   4:  </div>

Then, two CascadingDropDown extenders must be added to the page. One fills the first (vendors) list, and the other one fills the second (contacts) list. The following attributes must be set:

Depending on the programming language used, the name of the web service in question changes, but all other attribute values are the same. Here is the CascadingDropDown element for the first dropdown list:

[!code-aspxMain]

   1:  <ajaxToolkit:CascadingDropDown ID="ccd1" runat="server"
   2:   ServicePath="CascadingDropdown1.cs.asmx" ServiceMethod="GetVendors"
   3:   TargetControlID="VendorsList" Category="Vendor"
   4:   PromptText="Select Vendor" />

The control extenders for the second list need to set the ParentControlID attribute so that selecting an entry in the vendors list triggers loading associated elements in the contacts list.

[!code-aspxMain]

   1:  <ajaxToolkit:CascadingDropDown ID="ccd2" runat="server"
   2:   ServicePath="CascadingDropdown1.cs.asmx" ServiceMethod="GetContactsForVendor"
   3:   TargetControlID="ContactsList" ParentControlID="VendorsList"
   4:   Category="Contact"
   5:   PromptText="Select Contact" />

The actual work is then done in the web service, which is set up as follows. Note that the [ScriptService] attribute is used, otherwise ASP.NET AJAX cannot create the JavaScript proxy to access the web methods from client-side script code.

[!code-aspxMain]

   1:  <%@ WebService Language="C#" Class="CascadingDropdown1" %>
   2:  using System.Web.Script.Services;
   3:  using AjaxControlToolkit;
   4:  using System;
   5:  using System.Web;
   6:  using System.Web.Services;
   7:  using System.Web.Services.Protocols;
   8:  using System.Collections.Generic;
   9:  using System.Collections.Specialized;
  10:  using System.Data.SqlClient;
  11:  [ScriptService]
  12:  public class CascadingDropdown1 : System.Web.Services.WebService
  13:  {
  14:   // ...
  15:  }

The signature of the web methods called by CascadingDropDown is as follows:

[!code-csharpMain]

   1:  public CascadingDropDownNameValue[] MethodNameHere(string knownCategoryValues, 
   2:      string category)

So the return value must be an array of type CascadingDropDownNameValue which is defined by the Control Toolkit. The GetVendors() method is quite easy to implement: The code connects to the AdventureWorks database and queries the first 25 vendors. The first parameter in the CascadingDropDownNameValue constructor is the caption of the list entry, the second one its value (value attribute in HTML???s <option> element). Here is the code:

[!code-csharpMain]

   1:  [WebMethod]
   2:  public CascadingDropDownNameValue[] GetVendors(string knownCategoryValues, string category)
   3:  {
   4:      SqlConnection conn = new SqlConnection("server=(local)\\SQLEXPRESS; 
   5:      Integrated Security=true; Initial Catalog=AdventureWorks");
   6:      conn.Open();
   7:      SqlCommand comm = new SqlCommand("SELECT TOP 25 VendorID, Name 
   8:      FROM Purchasing.Vendor",conn);
   9:      SqlDataReader dr = comm.ExecuteReader();
  10:      List<CascadingDropDownNameValue> l = new List<CascadingDropDownNameValue>();
  11:      while (dr.Read())
  12:      {
  13:          l.Add(new CascadingDropDownNameValue(dr["Name"].ToString(),
  14:          dr["VendorID"].ToString()));
  15:      }
  16:      conn.Close();
  17:      return l.ToArray();
  18:  }

Getting the associated contacts for a vendor (method name: GetContactsForVendor()) is a bit trickier. First of all, the vendor which has been selected in the first dropdown list must be determined. The Control Toolkit defines a helper method for that task: The ParseKnownCategoryValuesString() method returns a StringDictionary element with the dropdown data:

[!code-csharpMain]

   1:  [WebMethod]
   2:  public CascadingDropDownNameValue[] GetContactsForVendor(string knownCategoryValues, 
   3:      string category)
   4:  {
   5:      int VendorID;
   6:      CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

For security reasons, this data must be validated first. So if there is a Vendor entry (because the Category property of the first CascadingDropDown element is set to "Vendor"), the ID of the selected vendor may be retrieved:

[!code-csharpMain]

   1:  if (!kv.ContainsKey("Vendor") || !Int32.TryParse(kv["Vendor"],out VendorID)) 
   2:  {
   3:      throw new ArgumentException("Couldn't find vendor.");
   4:  };

The rest of the method is fairly straight-forward, then. The vendor???s ID is used as a parameter for an SQL query that retrieves all associated contacts for that vendor. Once again, the method returns an array of type CascadingDropDownNameValue.

[!code-csharpMain]

   1:  SqlConnection conn = new SqlConnection("server=(local)\\SQLEXPRESS; 
   2:   Integrated Security=true; Initial Catalog=AdventureWorks");
   3:   conn.Open();
   4:   SqlCommand comm = new SqlCommand("SELECT Person.Contact.ContactID, FirstName, LastName 
   5:   FROM Person.Contact,Purchasing.VendorContact 
   6:   WHERE VendorID=@VendorID 
   7:   AND Person.Contact.ContactID=Purchasing.VendorContact.ContactID",conn);
   8:   comm.Parameters.AddWithValue("@VendorID", VendorID);
   9:   SqlDataReader dr = comm.ExecuteReader();
  10:   List<CascadingDropDownNameValue> l = new List<CascadingDropDownNameValue>();
  11:   while (dr.Read())
  12:   {
  13:   l.Add(new CascadingDropDownNameValue(
  14:   dr["FirstName"].ToString() + " " + dr["LastName"].ToString(),
  15:   dr["ContactID"].ToString()));
  16:   }
  17:   conn.Close();
  18:   return l.ToArray();
  19:  }

Load the ASP.NET page, and after a short while the vendor list is filled with 25 entries. Pick one entry and notice how the second dropdown list is filled with data.

The first list is filled automatically

The first list is filled automatically (Click to view full-size image)

The second list is filled according to the selection in the first list

The second list is filled according to the selection in the first list (Click to view full-size image)

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-forms/overview/ajax-control-toolkit/cascadingdropdown/using-cascadingdropdown-with-a-database-cs.htm
< THANKS ME>