将onclick事件添加到动态创建的链接按钮

时间:2011-02-01 20:09:04

标签: c# asp.net

我想要完成的是使用onClick命令设置我动态创建的链接按钮,这样点击它时会在后面的代码中运行一个方法。这是我的代码:

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;
}

2 个答案:

答案 0 :(得分:1)

Page_PreInit 处理程序中创建所有动态链接,并在每个页面上重新发布相同的层次结构。然后 ASP.NET 将能够处理动态链接的 OnClick 事件。
你不需要这个

lnkPost.Attributes.Add("runat", "server");

也许ASP.NET菜单控件会更合适?它支持XML与XPath的绑定

答案 1 :(得分:-1)

此示例添加一个按钮,并将单击的功能设置为“删除”,单击时将删除新按钮...

请参阅:Bind a click to a dynamic button with jQuery?

function addNewButton() {
  $("sweet_selector_here").append("<input type='button' id='sweetness' value='press me, i am awesome' />");
  $("#sweetness").click(function() {
    $(this).remove();
  });
}