Hi Friends,In this example i would like to explain how to create controls(Label,TextBox,DropDownList) dynamically.
For this i took 1 button(Access) & place holder control on the form.
Code under page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
else
{
createDynamicControls();
}
}
Code for method createDynamicControls():
protected void createDynamicControls()
{
Label lblCompanyName = new Label();
lblCompanyName.ID="lblCName1";
lblCompanyName.Style.Add("left", "15px");
lblCompanyName.Text = "Company Name:";
pholder1.Controls.Add(lblCompanyName);
TextBox txtCompanyName = new TextBox();
txtCompanyName.ID = "txtCName1";
txtCompanyName.Style.Add("left", "60px");
pholder1.Controls.Add(txtCompanyName);
Label lblCountry= new Label();
lblCountry.ID="lblCountry1";
lblCountry.Style.Add("left", "495px");
lblCountry.Text = "Country:";
pholder1.Controls.Add(lblCountry);
DropDownList ddlCountry= new DropDownList();
ddlCountry.ID = "ddlCountry1";
ddlCountry.Style.Add("left", "540px");
ddlCountry.Style.Add("width", "120px");
ddlCountry.Items.Add("Select");
ddlCountry.Items.Add("India");
ddlCountry.Items.Add("Srilanka");
ddlCountry.Items.Add("Bangladesh");
pholder1.Controls.Add(ddlCountry);
}
Code under AccessButton click event:
protected void AccessButton_Click(object sender, EventArgs e)
{
TextBox txtCompany = pholder1.FindControl("txtCName1") as TextBox;
DropDownList ddlCountry = pholder1.FindControl("ddlCountry1") as DropDownList;
}
Note:
* We can't access controls directly.For this we can add controls to PlaceHolder.From this PlaceHolder we can access controls.
Thank You...