In my last article AJAX IN ACTION I discussed some of the cool features of AJAX. In this article I will present that how you can make one DropDownList dependent on another DropDownList. Hence, when you change the item in the DropDownList the other DropDownList gets populated depending on the selection of the first DropDownList.

Introduction:

In my last article AJAX IN ACTION I discussed some of the cool features of AJAX. In this article I will present that how you can make one DropDownList dependent on another DropDownList. Hence, when you change the item in the DropDownList the other DropDownList gets populated depending on the selection of the first DropDownList.

AJAX IN ACTION:

The code to fill the DropDownList is already explained in the last article AJAX IN ACTION. Let's see how we can fill the second DropDownList depending on the selection of the first DropDownList.

Here is the server side method which is called whenever the selection of the first DropDownList changes.

[Ajax.AjaxMethod]
        
public DataSet GetProductsByCategoryID(int categoryID) 
        { 
            
string query = "SELECT ProductName FROM Products WHERE CategoryID = @CategoryID"; 
            SqlConnection myConnection = 
new SqlConnection(GetConnectionString()); 
            SqlCommand myCommand = 
new SqlCommand(query,myConnection); 
            myCommand.Parameters.Add("@CategoryID",categoryID); 
            SqlDataAdapter ad = 
new SqlDataAdapter(myCommand); 
            DataSet ds = 
new DataSet(); 
            ad.Fill(ds); 
            
return ds; 
        }
 

Now let's see how we call this method using the JavaScript code.

function GetProducts(index) 

    
    AjaxDemo.GetProductsByCategoryID(index,GetProducts_CallBack); 
}

function GetProducts_CallBack(response) 
{
    var ds = response.
value
            var html = 
new Array(); 
                    
            
if(ds!= null && typeof(ds) == "object" && ds.Tables!= null
            {
                
for(var i=0;i<ds.Tables[0].Rows.length;i++) 
                {
                    
                    html[html.length] = "<option value=" + ds.Tables[0].Rows[i].ProductID + ">" + ds.Tables[0].Rows[i].ProductName + "</option>"; 
                                
                }
                
                document.getElementById("Display1").innerHTML = "<select id=\"sel1\">" + html.join("") + "</select>";      
            }
 }
 

This is pretty much it. Now when you make the selection in the first DropDownList the other DropDownList is filled with new data which is fetched from the database.

I strongly encourage you to read my previous article ACTION IN ACTION in which I covered everything in details. Also don't forget to download the zip file which contains the complete code for this project.

I hope you liked the article, happy coding!