I have referred Error with the event handlers of dynamic linkbutton . It says to add event handlers in Page_Init
or Page_Load
. I tired following code. But the event handler is not fired when I click on the dynamic added link buttons. What need to be corrected here?
Note: The dynamic LinkButton controls are added in the click event of a button after some business validations (the business code is not given for brevity)
Markup
<form id="form1" runat="server">
<div>
<asp:LinkButton ID="lnkTest" runat="server" OnClick="LinkButton_Click">Static LinkButton</asp:LinkButton>
<br />
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
<br />
<asp:PlaceHolder ID="plhDynamicLinks" runat="server"></asp:PlaceHolder>
</div>
</form>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
foreach (Control ctrl in plhDynamicLinks.Controls)
{
LinkButton dynamicButton = (LinkButton)ctrl;
dynamicButton.Click += new EventHandler(LinkButton_Click);
}
if (Page.IsPostBack)
{
}
}
protected void Page_Init(object sender, EventArgs e)
{
int x = 0;
foreach (Control ctrl in plhDynamicLinks.Controls)
{
LinkButton dynamicButton = (LinkButton)ctrl;
dynamicButton.Click += new EventHandler(LinkButton_Click);
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
LinkButton clickedControl = (LinkButton)sender;
Response.Write(clickedControl.ID +" Link Button Clicked");
}
protected void btnAdd_Click(object sender, EventArgs e)
{
plhDynamicLinks.Controls.Clear();
LinkButton button1 = new LinkButton();
button1.ID = "D1";
button1.Text = "1";
plhDynamicLinks.Controls.Add(button1);
LinkButton button2 = new LinkButton();
button2.ID = "D2";
button2.Text = "2";
plhDynamicLinks.Controls.Add(button2);
}