HomeLearnASP.NET AJAX VideosHow Do I: Use the ASP.NET AJAX CascadingDropDown Control Extender?  

[How Do I:] Use the ASP.NET AJAX CascadingDropDown Control Extender?

Please install Silverlight or click download to watch video locally.

This video demonstrates how ASP.NET's standard DropDownList can become AJAX-enabled using the CascadingDropDown control extender from the ASP.NET AJAX Control Toolkit. You will also see how easy it is for a web form to draw its data from an XML Web Service.

Presented by Joe Stagner

Duration: 27 minutes, 56 seconds

Date: 24 January 2007

Watch    Video   |   Download    Video   |   VB Code    C# Code

Video downloads: WMV  |  Zune  |  iPod  |  PSP  |  MPEG-4  |  3GP

Audio downloads: AAC  |  WMA  |  MPEG-4  |  MPEG-3  |  MPEG-2

Comments : 85

Leave a Comment

polaw : On March 04, 2008 9:41 PM said:

I found this much more helpful than the article located at www.asp.net/.../CCDWithDB.aspx

Although, the other article gave me a vague idea of the concept, it left me with more questions than answers.

I will watch this a couple more times and re-create the code shown in order to both learn how to do this and create a re-usable portion of code.

Thanks to Joe

JoeStagner : On March 15, 2008 12:54 PM said:

Glad it was usefull - THANKS !

nehaljain : On March 21, 2008 4:33 PM said:

This is very helpful video. Just a note that the code link shown is not matching with the code shown during presentation. I followed each step to create the same and I am able to populate the first drop down but corresponding values are not loaded in second drop down. Are category values are case sensitive? I will try to debug it through.

I will definately watch other similar video posted by Joe

JoeStagner : On March 22, 2008 11:29 AM said:

Just a note: The videos is recorded with the programming done in VB. The C# code is written later to accomplish the same task.

Rajska : On March 30, 2008 12:29 PM said:

Hello Joe,

I did 4 dropdownlist boxes in VB for World Regions, Countries, States/Provinces and Cities. It works.

I made a new one in C# as required by ASP.Net 3.5, but now all I get are method errors 500, 12030s. Any suggestions?

Thanks.

Rajska : On March 30, 2008 2:16 PM said:

Addendum:

I get this error report:

Error 1 File 'WorldService.asmx' was not found.

How do I make it be found?

Rajska : On March 30, 2008 8:03 PM said:

Ok, I solved problems of the first 3 dropdownlist boxes by placing a "~/" in front of the asmx file.  But the last 4th box still gives Method error 500 or 12031.

JoeStagner : On March 31, 2008 9:37 AM said:

500 is a server error which means there is a problem in your Service Code.

This can be caused either by a prgramming defect or by failing to correctly attribute the Service Class with the ScriptService attributes.

realjuancho : On April 07, 2008 2:35 PM said:

Hey Joe, im a newcomer at this whole ASP AJAX stuff

i have a little question, where is the GetDropDownContentsPageMethod in the C# Code?

JoeStagner : On April 14, 2008 8:53 PM said:

It's all the way to the bottom of Default.aspx.cs

Musafiir : On April 15, 2008 3:38 AM said:

Thx a lot for the tutorials Joe Stagner.

In your tutorial when setting the "ServiceMethod" for the dropdownlist2, you have used "GetDropDownListContentsPageMethod". What would be the result if we use only "GetDropDownListContents" and specifying the service path "CarsService.asmx"?

Am doing a page whereby the user will type a product name which will automatically update a dropdownlist Location where that particular product is found. There is a connection to a database. Can you please guide me what should i modify to bind it to database or if there is a similar tutorial somewhere.

Thnx Joe, waiting for your response

idanz : On April 17, 2008 4:24 PM said:

Hello Joe,

Do you know what the [Method Error 12030] means to?

agnomonus : On April 23, 2008 11:49 PM said:

I appreciated the video and followed very closely. When I launched my app however the dropdownlists were populated progressively with each selection before it, but for the life of me I can't get the label to display the final text. I've looked at the downloaded source and my code is identical but the label displays nothing. Any ideas about that?

chjk : On April 25, 2008 9:12 AM said:

it's so cool.THANKS Joe!

i have a question:

If i add a new chidnode "TheFirstOwner" in the node "color",seem this:

 <make name="Acura">

   <model name="Integra">

     <color name="Green">

       <TheFirstOwner name="Joe Stagner" />

     </color >

     ...

 </make>

</CarsService>

i want to know how to dispay the "TheFirstOwner" item in

the Label1 in the DropDownList3_SelectedIndexChanged

event?

thank you very much!

chjk : On April 25, 2008 9:18 AM said:

if i choose Acura--Integra--Green

Label1.txet will display:

"You have chosen a Green Acura Green . Nice car! The First Owner is Joe Stagner"

Hideyoshi : On May 06, 2008 4:33 AM said:

To Joe,

the attribute of the Service Class with the ScriptService attributes is compulsary in the webservice.vb file? I'm facing the problem of method error 500 too. i'm Using SQL Server 2005 as my database.

Rajska : On May 07, 2008 5:43 PM said:

Same problem with Musafiir. How to data bind the selectedvalue to the database?  Will this work?  Add DataTextField="Make" SelectedValue='<%#Bind("Make") %>'  to the asp:DropDownList.

Or can SelectedValue='<%Bind("Make")%>' be added in the code-behind?

the_N_Channel : On May 14, 2008 8:02 AM said:

Ok, so the 500 error is a Server error...now I'm getting a 405 error. I went into the Toolkit code to try to find the dictionary that has the relationship between these numbers and what they mean, but it didn't seem to be in the CascadingDropDown...where can one find the information to decode these numbers? Generic numeric error messages is very Therac-25!

charnata : On May 15, 2008 1:00 PM said:

OK, I narrow down the issue I beleive but I do not know how to fix it or where to start.  In my third dropdown box the ParentControlID will not recongnize the dropdown box ID.  If I switch the third box to the first box it fill its box with selections based on the first dropdown box.  Can anyone give me an idea of where to look to correct this?

Thanks

stapes : On May 16, 2008 12:05 PM said:

Hi

The downloaded C# code has a bad zip header. Is it corrupt?

Also, where is the C# code for GetDropDownContentsPageMethod - its not on the video or in the downloaded code. i.e. this stuff:

<script runat="server">

       <System.Web.Services.WebMethod()>

       <System.Web.Script.Services.ScriptMethod()>

       public Shared function GetDropDownContentsPageMethod(ByVal knownCategoryValues as string, ByVal Category as string) As AjaxControlToolkit.CascadingDropDownNameValue()

           return new CarsService().GetDropDownContents(knownCategoryValues, category)

       end function

       </script>

charnata : On May 16, 2008 1:18 PM said:

Yea... I found my issue other than myself, Duh!  Since I was using a single table that had a hierarchal data set I was referencing the same column name in each of my [WebMethod] coding blocks.  Since I needed to use this data I gave the column an alias in each of the data set calls change .cs and .aspx pages accordingly and bingo it works!  A user to have up to 8 dropdown boxes and they all are working off the parent dropdown.

sachinmanath : On May 21, 2008 4:45 AM said:

sir i am usring you control in my website but some time i am getting this error Sys.WebForms.PageRequestManagerParserErrorException

Can you tell me how can i solve this problem and where it is existing?

Please reply me

Thanks

sul125 : On May 22, 2008 5:08 PM said:

why everything has to be in ajax section in visual basic anguage?!!

why not any c# one

Loretta : On May 27, 2008 11:21 AM said:

When I try to download this video the ZIP file comes back corrupt.  When I try to save target as on the wmv file, I get the first 5 minutes of the video and then it just stops.  Is there something wrong with the WMV version of the video, or is it just me?

Thanks.

trisonics : On May 28, 2008 4:33 AM said:

thanks I was struggling with the implementation. Now its ok. But I am getting 'Method 500' error if the data size is large.

Can you please suggest a solution.

JoeStagner : On May 28, 2008 9:31 AM said:

At how large does the problem start to appear ?

trisonics : On May 29, 2008 1:48 AM said:

i am not sure about the size but I found a solution in another post

forums.asp.net/.../1706189.aspx

the below change in web.config solved by problem

<system.web.extensions><scripting>

   <webServices>

     <jsonSerialization maxJsonLength="5000000" />

   </webServices>

 </scripting>

 </system.web.extensions>

Ennair : On June 03, 2008 12:00 PM said:

Hi,

Has anybody been able to bind this example to a database through datasets and table adapters? Also, has anybody been able to use the Cascading DropDown Lists in a formview?

Thanks,

E

timwp : On June 08, 2008 10:52 AM said:

www.asp.net/.../CCDWithDB.aspx

use the url above to learn how to hook up the CDDL extender to a database through table adapters. if you need to learn about table adapters look at the data access tutorials in the learn section.

george_guitar : On June 08, 2008 11:46 PM said:

Hi Joe: I'm need help. Now I am attempting to use a example with my data. I have error [Method error 500]

This the WebService:

using System;

using System.Web;

using System.Collections;

using System.Collections.Generic;

using System.Collections.Specialized;

using System.Web.Script.Services;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Data;

using System.Data.SqlClient;

using AjaxControlToolkit;

/// <summary>

/// Servucio web que nos proporcionara el listado de Catagorias y sus productos

/// </summary>

[System.Web.Script.Services.ScriptService()]

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

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

   public CategoriesProducts () {

       //Eliminar la marca de comentario de la línea siguiente si utiliza los componentes diseñados

       //InitializeComponent();

   }

[WebMethod]

public CascadingDropDownNameValue[] GetCategories(string knowCategoryValues, string Category)

{

SqlConnection cnn;

SqlCommand cmd;

SqlDataReader dtr;

try

{

cnn=new SqlConnection("Data Source=ARBAWKS081; User Id=sa; Password=sa; Initial Catalog=NorthWind");

cnn.Open();

cmd = new SqlCommand("Select CategoryId, CategoryName From Categories");

cmd.Connection=cnn;

dtr=cmd.ExecuteReader(CommandBehavior.CloseConnection);

List Categorias =

new List();

if (dtr.Read() == true)

{

while (dtr.Read() == true)

{

Int32 CatId = (Int32)dtr.GetInt32(0);

string CatName = (string)dtr.GetString(1);

Categorias.Add(new CascadingDropDownNameValue(CatName, CatId.ToString()));

}

return Categorias.ToArray();

}

else

{

return null;

}

}

catch(Exception ex)

{

string msg = "";

msg = ex.Message;

return null;

}

}

[WebMethod]

public CascadingDropDownNameValue[] GetProducts(string knowCategoryValues, string Category)

{

SqlConnection cnn;

SqlCommand cmd;

SqlDataReader dtr;

try

{

StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knowCatego ryValues);

Int32 CatId;

if (!kv.ContainsKey("Category") || Int32.TryParse(kv["Category"],out CatId))

{

return null;

}

cnn=new SqlConnection("Data Source=ARBAWKS081; User Id=sa; Password=sa; Initial Catalog=NorthWind");

cnn.Open();

cmd = new SqlCommand("Select ProductId, ProductName From Products Where CategoryId = " + CatId.ToString() );

cmd.Connection=cnn;

dtr=cmd.ExecuteReader(CommandBehavior.CloseConnection);

List Products =

new List();

if (dtr.Read() == true)

{

while (dtr.Read() == true)

{

Int32 ProdId = (Int32)dtr.GetInt32(0);

string ProdName = (string)dtr.GetString(1);

Products.Add(new CascadingDropDownNameValue(ProdName, ProdId.ToString()));

}

return Products.ToArray();

}

else

{

return null;

}

}

catch(Exception ex)

{

string msg = "";

msg = ex.Message;

return null;

}

}

}

This aspx Page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

">www.w3.org/.../xhtml11.dtd">

">www.w3.org/.../xhtml">

   Untitled Page

Categoria       

Productos       

ID="CascadingDropDown1"

runat="server"

Category="Category"

PromptText="Seleccione una categoría"

LoadingText="Cargando categorías"

TargetControlID="cboCategories"

ServiceMethod="GetCategories"

ServicePath="CategoriesProducts.asmx">

ID="CascadingDropDown2"

runat="server"

Category="Products"

PromptText="Seleccione un producto"

LoadingText="Cargando productos..."

TargetControlID="cboProducts"

ParentControlID="cboCategories"

ServiceMethod="GetProducts"

ServicePath="CategoriesProducts.asmx">

</cc1:CascadingDropDown>

</ContentTemplate>

</asp:UpdatePanel>

</div>

</form>

</body>

</html>

Please: Say me where be error. I'm sorry for my english. I'm from Peru and no speak english very good.

Thanks You

mmikhail : On June 16, 2008 8:28 AM said:

I have been playing with this for a bit and it seems to me that the signature variable names can NOT be changed in any way.  They must be 'knownCategoryValues' and 'category'.  For example:

Public Shared Function getAssistWC(ByVal knownCategoryValues As String, ByVal category As String) As AjaxControlToolkit.CascadingDropDownNameValue()

if you change it, the code will throw an 500 error.  Is this right?

soulflyryan : On June 20, 2008 12:48 AM said:

Hi Joe...

Web service is needed in order for the cascading dropdown to work? or even in class it will work...

I mean the code that load the data to dropdown must be in webservice or it is also ok if it is place in a class...

Please help me,because it gives me error...

Tnx

.NETFreak : On June 27, 2008 11:33 AM said:

Hats off to Joe for the view. Thnx a bunch Joe.

Sivva : On June 30, 2008 12:41 AM said:

Hi Joe,

The video was great...

Many ppl hv already asked the question:

Could you pls clarify:

whats the diff between the methods "GetDropDownContents" and "GetDropDownContentsPageMethod" since both need the web service call.

Thanks,

Sivva

mohaa_tom : On June 30, 2008 5:34 PM said:

Sivva, while I can't adequately explain the technical difference I can explain the way it works based on observation.

The GetDropDownContentsPageMethod is a method within the actual page, it invokes the web service's method GetDropDownContents.  

By putting [WebMethod] in the page's code behind, I am assuming it makes an asynchronous callback to that method, it invokes the web service method and VOILA, the drop down is filled with appropriate list items relevant to the selection made in the parent control.

Careful though.  Because I noticed when the page has been loaded as a result of a Server.Transfer, the client is unaware of this.  Let me explain.

I have a home page, default.aspx at the root, and a button on it to allow users to register.  The code behind on that page executes Server.Transfer("/register/register.aspx")

My client loads the correct page and the primary drop down and cascading dropdown extender makes it's call to the webservice and is loaded with data.

When I selected a value from the primary drop down, the CascadingDropdown2 control for the secondary dropdown initiates the directive in the ServiceMethod property - which is the name of the page method.

The problem I noticed is that it attempts to execute a page method in my default.aspx page, the page doesn't have that method so I get a [Method 500] error.

v/r

Tom

mohaa_tom : On June 30, 2008 5:52 PM said:

Joe,

Thanks for the video.  I am successfully using two CascadingDropDown extenders, supporting respective dropdowns.

My workaround for the problem I've described in my attempt to assist Sivva was to use the actual ServicePath and ServiceMethod as opposed to just the ServiceMethod using the WebMethod coded in the page GetDropDownContentsPageMethod.  It works well.  Until I actually try and submit the page.

Then I get the "Invalid Postback" error.  Two questions.

1.  Did I cause this by not using the GetDropDownContentsPageMethod ?  Which I felt compelled to not use due to the Server.Transfer issue.

2.  Is <%@ page enableeventvalidation="false" %> the only way to avoid the Invalid Postback error ?

Thanks

v/r

Tom

pnv.ravikiran : On July 02, 2008 1:30 AM said:

good one, thanks joe

rizasirman : On July 16, 2008 9:34 AM said:

hello,

I'm using c# in my ASP.NET applications. And this video is based on VB. Do you think to publish a C# based video tutorial, to let us learn writing web references easily

himavath : On July 17, 2008 10:09 PM said:

Hi,

Thanks for the video.  I am successfully able to use CascadingDropDown extenders

I have a question.

If I use all these controls in user control I am not able to set <%@ page enableeventvalidation="false" %> as usercontrol doesn't support can you please help how to fire events

Lacidian : On July 20, 2008 11:48 AM said:

How can I test out the web service.  I am trying to view the format of string the web services output.

reference:

/CascadingDropDown/CarsService.asmx?op=GetDropDownContents

knownCategoryValues: Make

category: Make

but that is the only "test" I can make work.

I wanted to view the output of the web service, So I could better understand how the AJAX control is using the data to populate the drop-down boxes.

No other variation of the asmx paramters worked.  knownCategoryValues / category

Thanks,

Doug Lubey

Lacidian : On July 20, 2008 1:37 PM said:

Ok. So I decided to run the application on my localhost in debug mode.  And put a break point on the webservice.

Found out how the data is returned and also called upon in the web service.

Example format is as follows:

KnowCategoryValues = Make:Acura;

Category = Model

KnowCategoryValues = Make:Acura;Model:Integra;

Category = Color

What I really trying to develop is my own custom web service either by xml or by database calls using the cascadingDropDown.

-Doug Lubey of Louisiana

       

macupryk : On August 03, 2008 12:19 AM said:

hi guys i am problems with the following questions.

I need to populate the cddDay where it takes two parameters from the other cascading drop downs

GetDayList ==> how should i modify the below code for this to work.

               TargetControlId="ddlMonth"

               LoadingText="[Loading Months...]"

               ServicePath="../LocationService.asmx"

               ServiceMethod="GetMonthList" Enabled="True" />

           

               TargetControlId="ddlYear"

               LoadingText="[Loading Year...]"

               ServicePath="../LocationService.asmx"

               ServiceMethod="GetYearList" Enabled="True" />

           

               TargetControlId="ddlDay"

               LoadingText="[Loading Year...]"

               ServicePath="../LocationService.asmx"

               ServiceMethod="GetDayList" Enabled="True" />

       

          

          

         </asp:DropDownList>&nbsp;

 [WebMethod(Description = "Populate a year list.")]

   [System.Web.Script.Services.ScriptMethod]

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

   {

       List<CascadingDropDownNameValue> yearList = new List<CascadingDropDownNameValue>();

       // Year list can be changed by changing the lower and upper

       // limits of the For statement

       int i = 1;

       for (int intYear = DateTime.Now.Year - 18; intYear >= DateTime.Now.Year - 99; intYear--)

       {

           yearList.Add(new CascadingDropDownNameValue(intYear.ToString(), (i++).ToString()));

       }

       return yearList.ToArray();

   }

   /////////////////////////////////////////////////////////// ////////////////////////////

   [WebMethod(Description = "Populate a month list.")]

   [System.Web.Script.Services.ScriptMethod]

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

   {

       List<CascadingDropDownNameValue> monthList = new List<CascadingDropDownNameValue>();

       monthList.Add(new CascadingDropDownNameValue("January", "1"));

       monthList.Add(new CascadingDropDownNameValue("February", "2"));

       monthList.Add(new CascadingDropDownNameValue("March", "3"));

       monthList.Add(new CascadingDropDownNameValue("April", "4"));

       monthList.Add(new CascadingDropDownNameValue("May", "5"));

       monthList.Add(new CascadingDropDownNameValue("June", "6"));

       monthList.Add(new CascadingDropDownNameValue("July", "7"));

       monthList.Add(new CascadingDropDownNameValue("August", "8"));

       monthList.Add(new CascadingDropDownNameValue("September", "9"));

       monthList.Add(new CascadingDropDownNameValue("October", "10"));

       monthList.Add(new CascadingDropDownNameValue("November", "11"));

       monthList.Add(new CascadingDropDownNameValue("December", "12"));

       return monthList.ToArray();

   }

   /////////////////////////////////////////////////////////// ////////////////////////////

   [WebMethod(Description = "Populate a days list for a specific month and year.")]

   [System.Web.Script.Services.ScriptMethod]

   public AjaxControlToolkit.CascadingDropDownNameValue[] GetDayList(string knownCategoryValues, string category, int year, int month)

   {

       List<CascadingDropDownNameValue> dayList = new List<CascadingDropDownNameValue>();

       int NumberOfDays = DateTime.DaysInMonth(year, month);

       for (int day = 1; day <= NumberOfDays; day++)

       {

           dayList.Add(new CascadingDropDownNameValue(day.ToString(), day.ToString()));

       }

       return dayList.ToArray();

   }

   /////////////////////////////////////////////////////////// //////////////////////////////

John Jiang : On August 04, 2008 2:42 PM said:

Joe:

Why there is no EnablePageMethods=True for  ScriptManager control. Can we call a page method from client script without this property set to True?

Thanks

John Jiang

littlepeak : On August 06, 2008 3:48 AM said:

cool vedio

cv_vikram : On August 06, 2008 1:25 PM said:

It is simple and good

billy.chen : On August 27, 2008 5:25 PM said:

Nice tutorial. Thanks!! I encounter an issue. If select a value with "/"(e.g., VW/Audi)in the level 1 dropdown, the level 2 dropdown gets [method error 550] errors. Take out "/" then it works fine. Could anyone helps? Thanks in advance!!

S.Pirashanth : On August 28, 2008 5:41 AM said:

Excellent video series. Thanks a lot

travich : On September 13, 2008 1:09 PM said:

I just don't know if this could be more frustrating.  For 2 days now I've been fighting with this Method Error 500 error.

People just love developing in the web, and I guess this is why I'm stuck in winforms.  I could have done this in what... four lines of C# code?  

*sighs*  Guess griping about it doesn't get me anywhere.  Better get back to it.

chitrasatheesh : On September 22, 2008 6:26 AM said:

i am not able to download this video..can anyone help me

zambi9999 : On October 03, 2008 5:19 PM said:

below is working ccd sample of called from pagemethods

DEFAULT.ASPX

============

<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" EnableEventValidation="false" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "">www.w3.org/.../xhtml11.dtd">

">www.w3.org/.../xhtml">

   CCD Try

   

       

       

           

               

                   

                       ServiceMethod="GetAuthorsDropDownContents" PromptText="Please select an author" />

                   Author:

                   

                   

                       TargetControlID="ddlTitle" UseContextKey="True" Category="Titles" ParentControlID="ddlAuthor"

                       PromptText="Please select an author">

                   

                   

                   Title:

                   

                   </asp:DropDownList>

               </ContentTemplate>

           </asp:UpdatePanel>

       </div>

   </form>

</body>

</html>

CODEBEHIND

==========

Imports System.Data

Imports System.Data.SqlClient

Imports System.Collections

Imports System.Collections.Generic

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

Imports AjaxControlToolkit

Partial Class _Default

   Inherits System.Web.UI.Page

   Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

   End Sub

   <System.Web.Services.WebMethod()> _

   <System.Web.Script.Services.ScriptMethod()> _

   Public Shared Function GetTitleDropDownContents(ByVal knownCategoryValues As String, ByVal category As String) As AjaxControlToolkit.CascadingDropDownNameValue()

       Dim strSQL As String

       Dim i As Int32

       Dim auid As String = knownCategoryValues.Split(CChar(":"))(1).Replace(";", "")

       strSQL = "select titles.title_id, title from titles "

       strSQL = strSQL & " inner join titleauthor on titles.title_id = titleauthor.title_id "

       strSQL = strSQL & " inner join authors on titleauthor.au_id = authors.au_id "

       strSQL = strSQL & " where authors.au_id = '" & auid & "'"

       Dim dttable As DataTable = getdata(strSQL)

       Dim kv As StringDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValu esString(knownCategoryValues)

       If Not (kv.ContainsKey("Author")) Then

           Return Nothing

       End If

       Dim _Titles As New List(Of AjaxControlToolkit.CascadingDropDownNameValue)

       For i = 0 To dttable.Rows.Count - 1

           _Titles.Add(New AjaxControlToolkit.CascadingDropDownNameValue(dttable.Rows( i)("title").ToString(), dttable.Rows(i)("title_id").ToString()))

       Next

       Return _Titles.ToArray()

   End Function

   Public Shared Function getdata(ByVal strSQL As String) As DataTable

       Dim readerData As SqlDataReader

       Dim connSQL As New SqlConnection

       Dim cmdSQL As New SqlCommand

       Dim dtTable As New DataTable

       Dim col As DataColumn

       Dim row As DataRow

       Dim i As Integer

       connSQL.ConnectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=Pubs;Integrated Security=SSPI;"

       connSQL.Open()

       cmdSQL.CommandText = strSQL

       cmdSQL.CommandType = CommandType.Text

       cmdSQL.Connection = connSQL

       readerData = cmdSQL.ExecuteReader()

      For i = 0 To readerData.FieldCount - 1

           col = New DataColumn()

           col.ColumnName = readerData.GetName(i)

           col.DataType = readerData.GetFieldType(i)

           dtTable.Columns.Add(col)

       Next

       While readerData.Read

           row = dtTable.NewRow()

           For i = 0 To readerData.FieldCount - 1

               If IsDBNull(readerData.Item(i)) = True Then

                   row(i) = ""

               Else

                   row(i) = readerData.Item(i).ToString.Trim

               End If

           Next

           dtTable.Rows.Add(row)

       End While

       Return dtTable

   End Function

   <System.Web.Services.WebMethod()> _

   <System.Web.Script.Services.ScriptMethod()> _

   Public Shared Function GetAuthorsDropDownContents(ByVal knownCategoryValues As String, ByVal category As String) As AjaxControlToolkit.CascadingDropDownNameValue()

       Dim i As Int32

       Dim strSQL As String

       strSQL = "select au_id, (au_lname + ', ' + au_fname) as auname from authors"

       Dim dttable As DataTable = getdata(strSQL)

       Dim _Author As New List(Of AjaxControlToolkit.CascadingDropDownNameValue)

       For i = 0 To dttable.Rows.Count - 1

           _Author.Add(New AjaxControlToolkit.CascadingDropDownNameValue(dttable.Rows( i)("auname").ToString(), dttable.Rows(i)("au_id").ToString()))

       Next

       Return _Author.ToArray()

   End Function

   Protected Sub ddlAuthor_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlAuthor.SelectedIndexChanged

       Call GetTitleDropDownContents(ddlAuthor.SelectedItem.Value, "Titles")

   End Sub

End Class

ibzmiller : On October 10, 2008 12:06 PM said:

Hi Guys,

In the video it you had to code for locking on the xml file. If this were a service that would be used by say a thousand users surely it would be locked all the time. Therefore not viable.

I only say this as I'm interested in using this functionality as part of a solution but, can't see why using an xml web service would be better than a call to the database.

Can you use this control with a database?

Cheers,

      Iain

hododi : On October 14, 2008 7:55 AM said:

hi...

rajesh_singh : On October 18, 2008 3:02 AM said:

Realy Nice.

You guys are doing gr8 work.

Keep it up.

Realy i appreciate it.

rajesh singh

djibril_chimere_DIAW : On October 21, 2008 5:52 AM said:

Thanks!

jwelsh : On October 21, 2008 3:25 PM said:

Hi Joe,

First let me say I really appreciate all the work you have done on these videos.  I've learned pretty much everything I know about Ajax from them!

I am trying to implement some cascading drop down lists based on your example.  It was working fine until I added an item to my XML file that contains a forward slash (/) in the name property.  When I select that value from the drop down, it puts a Method error 500 in the next drop down in line.  I can change the / to \ or | and it works fine, so I'm sure the / is the culprit.

Any ideas on this one?  Thanks again for all your help!

Eyveneen : On November 05, 2008 11:41 AM said:

Where is the video tutorial that references the security measure of authorizing events postback from server that was mentioned at the end of this tutorial video?

Eyveneen : On November 05, 2008 11:48 AM said:

Is this tutorial in lesson #7?

Eyveneen : On November 05, 2008 8:25 PM said:

Please select a Grade.[Method error 12031]  

Please select a Title[Method error 12031]

You have chosen [Method error 12031] [Method error 12031]. You may proceed

 So this is better than what i was getting earlier today.

:)

rizwan328 : On November 09, 2008 9:54 AM said:

My CascadingDropDown List in not binded....its howing [Method error 405].

rizwan328 : On November 09, 2008 10:47 AM said:

i just Note that web service is not called i am unable to trace the error why this is happening. i set break point in web service but control is not approaching web service. i confirmed that web service path is correct in CascadingDropDown and also methods name.....Can any body suggest the solution????

eXtension : On November 22, 2008 2:57 AM said:

Does anyone know why the values I set for PromptValue and EmptyValue are not being initialized? When my PromptText or EmptyText is being displayed, my values are "" instead of the ones I definied in the cascading control

jwelsh : On December 01, 2008 9:14 AM said:

Hi Joe,

Is there any way the comment section could be sorted with the newest ones at the top?  It might help us get more replies.

I'm still looking for an answer to my question regarding the Method Error 500 I get if I have a forward slash (/) in a drop down list with the CascadingDropDown extender attached.

Thanks!

eXtension : On December 03, 2008 9:10 PM said:

Yeah, placing the latest comments on the top is a great idea.

winter1984 : On December 13, 2008 11:29 PM said:

Hello, I am from China

formview + objectdatasource edit mode, can not be two-way binding, but only in Updating the formview, forced e.newValues set of values.

I would like to ask, there are other ways you

irfan12 : On December 29, 2008 3:13 AM said:

when i m trying to registred but they genrate error "user name already exist" plz send me step how to registred.

on my id msgtoirfan_12@yahoo.com.

ramalingam : On January 09, 2009 7:00 AM said:

asdcasfc

almny_com : On January 18, 2009 5:20 AM said:

thank you very muach

i serach for it to use it in my web site

http://www.almny.com

and i will copy your lesson to it

thanks again

salman_programmer@hotmail.com : On February 15, 2009 5:55 PM said:

This is Wonderful Joe........

I m just wondering that..cant it be implemented into class. Means with database connectivity that dropdownlists get data from database. i tried myself but there was Method error 500 or 12031. so i need ur help in this regard ..can u tell me how to solve this. thanks JOE in advance and waiting for you response.

salman_programmer@hotmail.com : On February 17, 2009 6:05 AM said:

can any body tell me........how to build the same application with the database connectivity ...... if any body has idea do let me know... or email me in the same ID.......thanks in advance .... and waiting for response

salman_programmer@hotmail.com : On February 17, 2009 2:34 PM said:

can any body tell me........how to build the same application with the database connectivity ...... if any body has idea do let me know... or email me in the same ID.......thanks in advance .... and waiting for response

SilverTrees : On February 22, 2009 9:33 PM said:

Thank you very much for this video. It all works just fine till I place in Formview. Under insert mode it works properly. The problem is under edit mode. What code can I add to your video that would enable the edit mode to work properly? I'm sure the error has to do with the binding of data on edit load. Just do not know what to do to correct this error.

Nkraj : On March 09, 2009 5:42 AM said:

Sir, I have create my own xml file. like in place of Make I have use Division And I want to build application. Please help me for the same.

Nkraj : On March 09, 2009 5:42 AM said:

Sir, I have create my own xml file. like in place of Make I have use Division And I want to build application. Please help me for the same.

Nkraj : On March 09, 2009 5:43 AM said:

Sir, I have create my own xml file. like in place of Make I have use Division And I want to build application. Please help me for the same. I have change the porperty of Dropdown as well services.vb file but its not working its quit urgent I will so thanks full if some one can help me.

Nkraj : On March 10, 2009 10:44 AM said:

hi may be this will help you to bind with database :

http://yasserzaid.wordpress.com/2009/01/03/ajax-cascading-dropdown-from-database/

Nkraj : On March 10, 2009 10:44 AM said:

hi may be this will help you to bind with database :

http://yasserzaid.wordpress.com/2009/01/03/ajax-cascading-dropdown-from-database/

dave_12345 : On March 10, 2009 5:54 PM said:

For all those still getting a "Method error 500" (or 12031) here are some simple things to check:

*That your _Document.Load() method contains a valid MapPath

(i.e you didn't change the name of your xml file to something else and that it IS in the App_Data folder)

*That all of the CascadingDropDown controls use "CarsService.asmx" (or whatever your .asmx file is entitled) as their ServicePath, remember it's case sensitive!

*That you have filled in the right property fields!! If like me you are using Visual Studio and not Visual Web Developer you will get more property fields for the CascadingDropDown controls, one simple error I made was filling in the PromptValue field instead of PromptText, doh!

ITIL : On March 18, 2009 1:28 PM said:

Question to experts i am totally new to asp.net, i want to learn very badly this language. Where should i start it? any good books online or to buy by the shop. Has anybody any idea!!!!!!!

PalanivelD : On April 24, 2009 7:14 AM said:

Excellent video. Thanks to Joe.

How you have added code snippet in toolbox..

stanobear : On April 27, 2009 5:11 PM said:

dave 12345,

brilliant stuff mate! I could pull off my hair until I was blue and could not find the error. It was of course in spelling of the _Document.Load()

Excelletn video Joe! You're the star!

Stan

smartclient007 : On September 13, 2009 2:32 AM said:

Joe...Thank you very much for this great video...great to see this feature..

ozkary : On September 18, 2009 5:55 PM said:

I am trying to stress test the web service that returns the CascadingDropDownNameValue collection. I noticed that using the proxy (net 2.0) class. The request payload is an xml document. The web method returns an empty payload.

If you use the ajax toolkit(client side), the request payload is a JSON string. The web method returns the right values. When using the proxy or the test page (the asmx?op=MyMethod), the debugger does not event step into the web method. When using the web page (client side ajax), the debugger steps into the code ok. This behavior only takes place for the CascaidingDropDown web method. All other web methods work ok.

Has anybody been able to use the proxy to call this method?

ozkary : On September 18, 2009 6:12 PM said:

The proxy works ok as well. The reference had not been updated with the latest web service definition.

rob_factorymaster : On October 02, 2009 10:06 AM said:

Just a little thing that I noticed today.

If you are having ERROR 500... Do a Find & Replace of "Name" and replace with "name", and "Value" to "value". And believe it or not, this actually removed my error!

Just thought I would share that with everyone! (Although, I would have thought the DLL should have had a .ToLower() put on it!

captain747480 : On November 11, 2009 11:41 AM said:

Does anyone know how to make a drop down list auto select if there is only one value?

For example, if I have a car model that is only available in 1 colour how do I get the colours drop down list to recognise this and automatically select the only colour available.

Leave a Comment

You must be logged in to leave a comment. Click here to log in.

Microsoft Communities