Adding dynamic controls in Asp.net

1.Declare public variables

static DropDownList[] drp_arr;
static int drp_count;

2.Write methods to develop dynamic controls

protected void add_dropdown(DropDownList drp)
{
try
{
//add to a container on the page
pnltitle.Controls.Add(drp);
//add a spacer after the control
pnltitle.Controls.Add(new LiteralControl(“<br><br>”));
}
catch (Exception ex)
{ }
}
private void createdropdown()
{
try
{
for (int i = 0; i < drp_arr.Length; i++)
{
//create a new instance of the control
DropDownList new_drp = new DropDownList();
new_drp.ID = “drp_title” + i.ToString();

new_drp.Items.Add(“Mr”);
new_drp.Items.Add(“Miss”);
new_drp.Items.Add(“Mrs”);

//add dropdown to dropdownarray
drp_arr[drp_count++] = new_drp;
//call our add function
add_dropdown(new_drp);

}
}
catch (Exception ex)
{ }
}

3.In the page_load event type the following code

drp_arr = new DropDownList[2];

{
if (drp_arr.Length > 0)
{
if (drp_arr[0] is DropDownList)
{
//for each DropDownList saved in our array, recreate it
foreach (DropDownList drp in drp_arr)
{
add_dropdown(drp);
}
}

createdropdown();
}
}
catch (Exception ex)
{

}

4. Bulid and run the page

Have a Happy Coding..

Permanent link to this article: https://blog.openshell.in/2011/02/adding-dynamic-controls-in-asp-net/

Leave a Reply

Your email address will not be published.