I need to add a Onclick
attribute to my LinkButton
which I am dynamically generating. How to add it?
Here is the code I came so far and struck with:
foreach(string i in List)//list has more than 50 data's
{
LinkButton link = new LinkButton();
link.Text = topics;
link.ID = topics;
link.Attributes.Add("runat", "server");
link.Click += new EventHandler(this.lnk_Click);
div_ID.Controls.Add(link);
div_ID.Controls.Add(new LiteralControl("<br />"));
}
public void lnk_Click(object sender,EventArgs e)
{
string ctrlId = ((Control)sender).ID;
GMethod(ctrlId); //handles some function in which i pass 开发者_StackOverflow中文版the id of the particular lnk button
}
I could call this lnk_Click
from my LinkButton
on dynamic generation. Its onclick attribute is not getting added to the link button. Please help me out on this guys. I am on urge.
You don't need to add the runat="server" attribute, as that will be done automatically. You've assigned the OnClick event handler, so you should be all set there too.
Since you're creating these controls dynamically, make sure that you have code in place to regenerate the LinkButton controls after postback, otherwise your event handler won't fire. Also make sure to assign the same IDs when regenerating it after postback.
I was also facing the same issue that the onClick event of the dynamically created hyperlink was not getting fired. I was making the mistake of placing the code of dynamic creation of hyperlink within "if(!IsPostBack)" and was assigning a random id to the hyperlink every time. So, please try assigning a unique ID and keep the code outside "if(!IsPostBack)". Will work.
精彩评论