Thursday, October 7, 2010

Dynamically Add a Control to the Page From a User Control

Dear Friend,

actualy this can't be done this way, because at this stage the page has loaded all the controls to build and it can't be modiified at this point as per the error message,you can do the following:
1- in the control page_load function place this line

this.Page.LoadComplete+=new EventHandler(addcont); // adds a function to the vent handler to be done after the page completes the loading

2- add this function which is used in the event handler above inside your control :
public void addcont(Object obj, EventArgs e)

{
Label newlable = new Label();

newlable.Text = "TestText here";
newlable.BackColor = System.Drawing.Color.Red;this.Page.Form.Controls.Add(newlable);

}

inside this function write all the controls you want to add to the page, this here adds a lable with a red background, with some test text in it..

I hope this helps,

please do not forget to mark my post as answer if it helps...

have a nice day,

No comments:

Post a Comment