My scenario: When adding dynamic controls to an UpdatePanel, their events are working properly.
But I want to add a new control to the UpdatePanel from another event (e.g. when a button is clicked).
To implement that, I need to add this control on the button event - but then the new control event do not work. On the other hand, I cannot do it on PageLoad - since it is called before the button event.
Therefore, the function RemoveProfession_Click isn't called on a LinkButton click
int number_of_buttons=3;
protected void Button1_Click(object sender, EventArgs e)
{
//here the value of number_of_buttons is changed
Update();
}
private void Update()
{
LinkButton[] lbRemove = new LinkButton[number_of_buttons];
for (int i = 0; i < number_of_buttons; i++)
{
Label lblProfession = new Label();
lblProfession.Text = "Label" + i;
PlaceHolder1.Controls.Add(lblProfession);
PlaceHolder1.Controls.Add(new LiteralControl(" "));
lbRemove[i] = new LinkButton();
lbRemove[i].Text = "remove";
lbRemove[i].CommandArgument = "" + i;
lbRemove[i].Click += new EventHandler(RemoveProfession_Click);
lbRemove[i].CausesValidation = false;
lbRemove[i].ID = "RemoveProfession" + i;
ScriptManager1.RegisterAsyncPostBackControl(lbRemove[i]);
PlaceHolder1.Controls.Add(lbRemove[i]);
PlaceHolder1.Controls.Add(new LiteralControl("<br/>"));
}
}
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="UpadtePanel1">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="PlaceHolder1">
<asp:Label runat="server" ID="Label1" Text="Text1"></asp:Label>
</asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" />