[英]add an onclick event to a dynamically created linkbutton
What I'm trying to accomplish is to set my dynamically created linkbutton with a onClick command so when click it will run a method in the code behind. 我想要完成的是使用onClick命令设置我动态创建的链接按钮,所以当单击它时将在后面的代码中运行一个方法。 This is my code:
这是我的代码:
protected void Page_Init(object sender, EventArgs e)
{
LoadLeftSide();
}
private void LoadLeftSide()
{
string filepath = Server.MapPath("DataSource.xml");
List<Post> list = PostHelper.GetAllPosts(filepath);
HtmlTable table = FindControl("tbl") as HtmlTable;
HtmlTableRow hearderrow = new HtmlTableRow();
HtmlTableCell heardercell = new HtmlTableCell();
heardercell.InnerText = "Posts:";
hearderrow.Cells.Add(heardercell);
table.Rows.Add(hearderrow);
foreach (Post p in list)
{
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell cell1 = new HtmlTableCell();
LinkButton lnkPost = new LinkButton();
lnkPost.ID =string.Format("{0}" ,Guid.NewGuid());
lnkPost.Attributes.Add("runat", "server");
lnkPost.Text = p.Title;
// lnkPost.CommandName = p.Id.ToString();
// lnkPost.CommandArgument = p.Id.ToString();
//lnkPost.Command += new CommandEventHandler(this.onLinkClick);
lnkPost.Click += new EventHandler(this.onLinkClick);
cell1.Controls.Add(lnkPost);
row.Cells.Add(cell1);
table.Rows.Add(row);
}
table.DataBind();
}
protected void onLinkClick(object sender, EventArgs e)
{
string filepath = Server.MapPath("DataSource.xml");
int id = 1;
Post post=PostHelper.GetPostById(id, filepath);
lblDescription.Text = post.Description;
}
Create all dynamic links in Page_PreInit handler and recreated the same hierarchy on every page post back. 在Page_PreInit处理程序中创建所有动态链接,并在每个页面上重新创建相同的层次结构。 Then ASP.NET will be able to process OnClick event of the dynamic link.
然后ASP.NET将能够处理动态链接的OnClick事件。
And you do not need this 你不需要这个
lnkPost.Attributes.Add("runat", "server");
Maybe ASP.NET Menu Control will be more suitable? 也许ASP.NET菜单控件会更合适? It supports binding from XML with XPath
它支持XML与XPath的绑定
This example adds a button and sets the clicked function to "remove" which removes the new button when clicked... 此示例添加一个按钮,并将单击的功能设置为“删除”,单击时删除新按钮...
see: Bind a click to a dynamic button with jQuery? 看: 用jQuery点击一个动态按钮?
function addNewButton() {
$("sweet_selector_here").append("<input type='button' id='sweetness' value='press me, i am awesome' />");
$("#sweetness").click(function() {
$(this).remove();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.