Click here to Skip to main content
15,745,432 members
Articles / Web Development / HTML
Posted 29 May 2007


18 bookmarked

Runtime Dependent ListBox

Rate me:
Please Sign up or sign in to vote.
3.00/5 (3 votes)
29 May 20071 min read
This articles describles how to add a Dependent ListBox in Runtime using Ajax (MagicAjax)

Screenshot - RuntimeDependentListBox.gif


From time to time, I have needed to have a listbox that depends on another listbox. And not only one for each form, but as many as I needed for each form. This article explains how to accomplish this.

Using the code

This code uses MagicAjax to handle the data without having to post the whole page. The function AddDependentListBox() creates a MagicAjax AjaxPanel in RunTime. DropDownList adds it to the AjaxPanel and then adds the AjaxPanel to the page. In this example a PlaceHolder is used, but a Table or any another control will also suffice.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using MagicAjax;

namespace RuntimeDependentListBox
    public class DependentListBox : System.Web.UI.Page
        protected System.Web.UI.WebControls.PlaceHolder ph;

        private void Page_Load(object sender, System.EventArgs e)
            //Put user code to initialize the page here
            //AddDependentListBox(Unique Key to find 
            //each dependent list box you want to add)
            //you can add as much as you want as long as 
            //you don't repeat the Key)


        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
            //CODEGEN: This call is required by the 
            //ASP.NET Web Form Designer.

        <summary />/// Required method for Designer support - do not modify</summary />
        <summary />/// the contents of this method with the code editor.</summary />
        <summary />/// </summary />
        <summary /></summary />private void InitializeComponent()
            this.Load += new System.EventHandler(this.Page_Load);

NOTE: When creating the first DropDownList, an EventHandler for the SelectedIndexChange is also created. This provides the DataBinding of the second DropDownList according to the value selected in the first. As a UniqueKey is provided in the AddDependentListBox() function, this lets the EventHandler know by the IDs which DropDownList to populate. This, in turn, lets the user add as many RunTime-dependent ListBoxes as he or she wants.

        private void AddDependentListBox(string pstrKey)
            //creates a MagicAjax AjaxPanel in Runtime that is unique for 
            //each DropDownList
            MagicAjax.UI.Controls.AjaxPanel ap = 
                new MagicAjax.UI.Controls.AjaxPanel();

            //This lines creates the First DropDownlist in Runtime
            DropDownList cboFirst = new DropDownList();
            cboFirst.ID = "1_" + pstrKey;
            cboFirst.AutoPostBack = true;

            //this add the EventHandler Function to the 
            //First Dependent List Box
            cboFirst.SelectedIndexChanged += new EventHandler(

            //Creation of teh second DropDownlist in RunTime
            DropDownList cboSecond = new DropDownList();
            cboSecond.ID = "2_" + pstrKey;
            cboSecond.Enabled = false;

            //Both DropDownLists are added to the 
            //MagicAjax AjaxPanel that was created

            //This line add the Created DropDownList to the PlaceHolder

            //This Line Populates First DropDownlist

        private void PopulateFirst(string pstrKey)
            //After adding to the PlaceHolder, you can find the 
            //created DropDownList in the Page with FindControl
            //and populate it as you want
            DropDownList cboFirst = (DropDownList)Page.FindControl(
                "1_" + pstrKey);
            cboFirst.Items.Add(new ListItem("Select",""));
            cboFirst.Items.Add(new ListItem("First Value","1"));
            cboFirst.Items.Add(new ListItem("Second Value","2"));

        private void cboFirst_SelectedIndexChanged(object sender, 
            System.EventArgs e)
            //if the index changes run this
            //the DropDownList changed
            DropDownList cboFirst = (DropDownList)sender;

            //Find the unique Key spliting the ID of the DropDownList
            string strKey = cboFirst.ID.Split('_')[1].ToString();

            //the second dropdownlist
            DropDownList cboSecond = (DropDownList)Page.FindControl(
                "2_" + strKey);

            //Poluates the Second DropDowList using the 
            //value selected from the First DropDownList
                PopulateSecond(strKey, cboFirst.SelectedValue.ToString());
                cboSecond.Enabled = true;
                cboSecond.Enabled = false;

        private void PopulateSecond(string pstrKey, string pstrcboFirstValue)
            //Populates the Second DropDownList accornding to the 
            //value selected from the first.
            DropDownList cboSecond = (DropDownList)Page.FindControl(
                "2_" + pstrKey);
                cboSecond.Items.Add(new ListItem(
                    "First Value Selected 1","1"));
                cboSecond.Items.Add(new ListItem(
                    "First Value Selected 2","2"));
                cboSecond.Items.Add(new ListItem(
                    "First Value Selected 3","3"));
            else if(pstrcboFirstValue=="2")
                cboSecond.Items.Add(new ListItem(
                    "Second Value Selected 1","1"));
                cboSecond.Items.Add(new ListItem(
                    "Second Value Selected 2","2"));

The creation of the MagicAjax AjaxPanel in Runtime for each group of dependent ListBoxes is what allows Ajax to load only the ListBoxes that are inside their AjaxPanel, without interfering in the others.


Well, that's it actually. Although the code is very simple, many developers feel strange about using controls created on the fly. However, this articles uses simple code to improve dependent ListBoxes using C# and Ajax.


  • v1.0 22/05/2007


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Written By
Software Developer I.ndigo -
Brazil Brazil
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

GeneralMy vote of 5 Pin
Manoj Kumar Choubey7-Feb-12 0:09
professionalManoj Kumar Choubey7-Feb-12 0:09 
GeneralChange the UI of ListBox and DropDownList on the fly Pin
elizas22-Mar-10 3:34
elizas22-Mar-10 3:34 
1. From ServerSide (In c#)

To change ListBox to DropDownList just change the Rows property of the ListBox with “1” Then it will behave as the Dropdown list in UI.
→ ListBox1.Rows = 1;

For the reverse Add
→ DropDownList1.Attributes.Add("size", "3");

2. In ClientSide (By Javascript)
DropDownList & Listbox Both rendered as select in the browser differentiate in their size property. So to change the UI of DropDownList to ListBox just change this property

function ToggleView()
document.getElementById('ListBox1').size = 1; // This will Change from listBox to Dropdown List.
document.getElementById('DropDownList1').size = 3;// This will Change from Dropdown List to listBox.
</ script>

A small may be useful idea can be: Save the page space by showing the options in a DropDownList & on mousover change it to listbox & again on mouseout do the reverse.
Here is the sample code

<asp:ListBox ID="ListBox1" runat="server" Rows="3" onmouseover="javascript:document.getElementById('ListBox1').size = 3;"
onmouseout ="javascript:document.getElementById('ListBox1').size = 1">
< asp:ListItem>Option 1</asp:ListItem>
< asp:ListItem>Option 2</asp:ListItem>
< asp:ListItem>Option 3</asp:ListItem>
</ asp:ListBox>
<a href=""></a>
<div class="signature">Cheers,

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.