Reputation: 3499
protected void addMoreDay_btn_Click(object sender, EventArgs e)
{
Control OneMoreDay = LoadControl("~/controls/Days/DayAdd.ascx");
Days_div.Controls.Add(OneMoreDay);
}
I load my userControl dynamically to a div element .. but the problem is that it works only once! .. I mean I click the addMoreDay_btn
button and it works then I try to click it again it won't create another instance of my control!
Edit
I think it works but it doesn't save the last created one .. it just replaces it with the newly created control .. and still I don't how to solve this! =S
Upvotes: 4
Views: 2271
Reputation: 49413
The problem is occurring because the dynamically added control is being destroyed on each postback right before it is created again. In order to have dynamic controls persist across postbacks, you'll have to add them every time the page posts back.
Try the following code. Notice that the controls are being added in the Page_Init method:
protected void addMoreDay_btn_Click(object sender, EventArgs e)
{
Control OneMoreDay = LoadControl("~/controls/Days/DayAdd.ascx");
Days_div.Controls.Add(OneMoreDay);
Session["MyControl"] += 1
}
protected void Page_Init(object sender, EventArgs e)
{
for (int i = 1; i <= (int)Session["MyControl"]; i++) {
Control OneMoreDay = LoadControl("~/controls/Days/DayAdd.ascx");
Days_div.Controls.Add(OneMoreDay);
}
}
See here
Upvotes: 5