In this article I will explain with an example, how to create Dynamic DropDownList control in ASP.Net using C# and VB.Net.
 
 

HTML Markup

The following HTML Markup consists of:
Panel – For adding dynamic DropDownList.
<asp:Panel ID="pnlControls" runat="server" BorderWidth="1" Width="300"></asp:Panel
 
 

Creating Dynamic LinkButton

Inside the Page_PreInit event handler, the Dynamic LinkButton is created and the ID, Text properties are set and Click event has been assigned to it and it is also added as control to the Form.
Finally, the RecreateControls is called and with required parameter i.e. control prefix and control type.
C#
protected void Page_PreInit(object sender, EventArgs e)
{
    //Create a Dynamic LinkButton to Add DropDownList.
    LinkButton lnkAdd = new LinkButton();
    lnkAdd.ID = "lnkAdd";
    lnkAdd.Text "Add DropDownList";
    lnkAdd.Click += new EventHandler(OnAdd);
    this.form1.Controls.Add(lnkAdd);
 
    //Recreate Controls.
    this.RecreateControls("ddlDynamic", "DropDownList");
}
 
VB.Net
Protected Sub Page_PreInit(ByVal sender As ObjectByVal e As EventArgs) Handles Me.PreInit
    'Create aLinkDynamic Button to Add TextBoxes.
    Dim lnkAdd As New LinkButton()
    lnkAdd.ID = "lnkAdd"
    lnkAdd.Text "Add DropDownList"
    AddHandler lnkAdd.ClickAddressOf OnAdd
    Me.form1.Controls.Add(lnkAdd)
 
    'Recreate Controls.
    Me.RecreateControls("ddlDynamic", "DropDownList")
End Sub
 
 

Adding Dynamic TextBox and DropDownList Controls

When Add button is clicked, the FindOccurence method is called where we pass Dynamic DropDownList as parameter and stored inside an integer variable.
Then, the CreateDropDownList method is called where we convert integer into string and pass as parameter.
Note: The FindOccurrence method is called inside the button Add event. It will be described later in the article.
C#
protected void OnAdd(object sender, EventArgs e)
{
    int cnt = this.FindOccurence("ddlDynamic");
    this.CreateDropDownList("ddlDynamic_" + Convert.ToString(cnt + 1));
}
 
VB.Net
Protected Sub OnAdd(ByVal sender As ObjectByVal e As EventArgs)
    Dim cnt As Integer = Me.FindOccurence("ddlDynamic")
    Me.CreateDropDownList("ddlDynamic_" & Convert.ToString(cnt + 1))
End Sub
 
 

Finding Occurrence of Dynamic Controls

The FindOccurrence function is used to calculate the count of occurrences of the substring that is passed to it in the Request.Form collection.
C#
private int FindOccurence(string substr)
{
    string reqstr Request.Form.ToString();
    return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
 
VB.Net
Private Function FindOccurence(ByVal substr As String) As Integer
    Dim reqstr As String Request.Form.ToString()
    Return ((reqstr.Length - reqstr.Replace(substr,"").Length) / substr.Length)
End Function
 
 

Creating Dynamic DropDownList on Dynamic LinkButton click

Inside this method the Dynamic DropDownList is created and ID property is set and ListItem are added.
The AutoPostBack property of the Dynamic DropDownList is set to true and the Add method is called where we pass Dynamic DropDownList as a parameter.
Then, the Literal object is created and the Add method is called where we pass Literal object as a parameter.
C#
private void CreateDropDownList(string id)
{
    DropDownList ddlAdd = new DropDownList();
    ddlAdd.ID = id;
    ddlAdd.Items.Add(new ListItem("--Select--", ""));
    ddlAdd.Items.Add(new ListItem("One", "1"));
    ddlAdd.Items.Add(new ListItem("Two", "2"));
    ddlAdd.Items.Add(new ListItem("Three", "3"));
    ddlAdd.AutoPostBack = true;
    ddlAdd.SelectedIndexChanged += new EventHandler(OnSelectedIndexChanged);
    pnlControls.Controls.Add(ddlAdd);
 
    Literal lt = new Literal();
    lt.Text "<br />";
    pnlControls.Controls.Add(lt);
}
 
VB.Net
Private Sub CreateDropDownList(ByVal id As String)
    Dim ddlAdd As New DropDownList()
    ddlAdd.ID = id
    ddlAdd.Items.Add(New ListItem("--Select--", ""))
    ddlAdd.Items.Add(New ListItem("One", "1"))
    ddlAdd.Items.Add(New ListItem("Two", "2"))
    ddlAdd.Items.Add(New ListItem("Three", "3"))
    ddlAdd.AutoPostBack = True
    AddHandler ddlAdd.SelectedIndexChangedAddressOf OnSelectedIndexChanged
    pnlControls.Controls.Add(ddlAdd)
 
    Dim lt As New Literal()
    lt.Text "<br />"
    pnlControls.Controls.Add(lt)
End Sub
 
 

Selected Changed DropDownList

When an Item is selected (changed) in the Dynamic DropDownList, first the Dynamic DropDownList is referenced and its ID is determined.
Finally, the ID of the Dynamic DropDownList is displayed using JavaScript Alert Message Box.
C#
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
    DropDownList ddlAdd = (DropDownList)sender;
    string id = ddlAdd.ID;
 
    //Place the functionality here.
    ClientScript.RegisterStartupScript(this.GetType(), "alert""alert('" + id + " fired SelectedIndexChanged event.');", true); 
}
 
VB.Net
Protected Sub OnSelectedIndexChanged(ByVal sender As ObjectByVal e As EventArgs)
    Dim ddlAdd As DropDownList = DirectCast(sender, DropDownList)
    Dim id As String = ddlAdd.ID
 
    'Place the functionality here.
    ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", "alert('" & id & " fired SelectedIndexChanged event.');", True)
End Sub
 
 

Recreating Dynamic Controls

The RecreateControls function consists of two parameters:
1. ctrlPrefix – The prefix used for the controls.
2. ctrlType – The type of control i.e. TextBox, DropDownList.
Inside the RecreateControls function, the FindOccurrence method is called and the control count is determined.
Based on the number of controls found, a FOR loop is executed over each item and then the check is performed if the control type is DropDownList then the CreateDropDownList method is called with ID as parameter.
Note: The IDs must be unique for each Dynamic control.
 
C#
private void RecreateControls(string ctrlPrefixstring ctrlType)
{
    string[]ctrls Request.Form.ToString().Split('&');
    int cnt = this.FindOccurence(ctrlPrefix);
    if (cnt > 0)
    {
        for (int k = 1; k <= cnt; k++)
        {
            for (int i = 0; i < ctrls.Length ctrls.Length; i++)
            {
                if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
                {
                    string ctrlID ctrls[i].Split('=')[0];
 
                    if (ctrlType == "DropDownList")
                    {
                        this.CreateDropDownList(ctrlID);
                    }
                    break;
                }
            }
        }
    }
} 
 
VB.Net
Private Sub RecreateControls(ByVal ctrlPrefix As StringByVal ctrlType As String)
    Dim ctrls As String() = Request.Form.ToString().Split("&"c)
    Dim cnt As Integer = Me.FindOccurence(ctrlPrefix)
    If cnt > 0 Then
        For k As Integer = 1 To cnt
            For i As Integer = 0 To ctrls.Length - 1
                If ctrls(i).Contains((ctrlPrefix & "-") + k.ToString()) AndAlso Not ctrls(i).Contains("EVENTTARGET") Then
                    Dim ctrlID As String ctrls(i).Split("="c)(0)
 
                    If ctrlType = "DropDownList" Then
                        Me.CreateDropDownList(ctrlID)
                    End If
                    Exit For
                End If
            Next
        Next
    End If
End Sub 
 
 

Screenshot

Creating Dynamic DropDownList Controls in ASP.Net
 
 

Downloads