Home Gitesh Portfolio Blog About Me Gallery Contact

Dynamically add a label, hyperlink, dropdown or any other items in codebehind

You need to keep a placeholder to hold these dynamic items in the body of your code.

Assembly Reference: using system.data

Create a label dynamically

Label CreatelabelName = newLabel();
CreatelabelName.Text = “OrderItemName”;          

Create a hyperlink Dynamically

HyperLink Createlink = newHyperLink();
Createlink.Enabled = true;
Createlink.Text = “OrderItemName”;
Createlink.NavigateUrl = "http://www.google.co.nz";
Createlink.Target = "_blank";

Creating a Dropdownlists dynamically

If the Dropdown already exists you can add one more item as below
To create a complete new dropdown from scratch
DropDownList ddl = newDropDownList();
ddl.ID = "DropDownID_Dynamic";
ddl.CssClass = "DropdownCSSClass1";

ddl.Items.Add(newListItem("--Select--", "--Select--")); ddl.Items.Add(newListItem("One", "One"));
ddl.Items.Add(newListItem("Two", "2"));
ddl.Items.Add(newListItem("Three", "3"));                   
//ddl.AutoPostBack = true;
ddl.SelectedIndexChanged += newEventHandler(ddl_SelectedIndexChanged);//We are creating an event handler here...So we can handle and event when dropdwon changes       
PlaceHolder1.Controls.Add(ddl);//Create a placeholder first
//Event handler for the dropdown – Found that sometimes creates issues with dynamic creation of dropdown – So create dropdown manually and then apply items dynamically
protectedvoidddl_SelectedIndexChanged(object sender, EventArgs e)
//var DropDownText = ddl.SelectedItem.Text;
//var DropDownValue = ddl.SelectedItem.Value;

Posted: 22/04/2013 9:17:01 p.m. by Gitesh Shah | with 0 comments