dynamically created list of link buttons, link buttons not posting back

别等时光非礼了梦想. 提交于 2019-11-30 15:50:30

问题


Hi I am dynamically creating link buttons in a 'ul li' list. I am then trying to tie each link button to a click event where i set a label to the text of the link button clicked. however the event that should fire doesnt get fired?

    if (!Page.IsPostBack)
        {
int listItemIds = 0;
       foreach (Node productcolour in product.Children)
       {
           HtmlGenericControl li = new HtmlGenericControl("li");
           LinkButton lnk = new LinkButton();
           lnk.ID = "lnk" + listItemIds;
           lnk.Text = productcolour.Name;
           lnk.Click += new EventHandler(Clicked);
           //lnk.Command += new CommandEventHandler(lnkColourAlternative_Click);
           //lnk.Click 
           li.Controls.Add(lnk);
           ul1.Controls.Add(li);
           listItemIds++;
       }
}

the above is wrapped within a if(!page.ispostback) and the label text is never set anywhere else. heres to the event

protected void Clicked(object sender, EventArgs e)
{
    LinkButton lno = sender as LinkButton;
    litSelectedColour.Text = lno.Text;

}

回答1:


Code must run on each postback:

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        int listItemIds = 1;

        for (int i = 0; i < 10; i++)
        {
            var li = new HtmlGenericControl("li");
            var lnk = new LinkButton();

            lnk.ID = "lnk" + listItemIds;
            lnk.Text = "text" + i;
            lnk.Click += Clicked;
            //lnk.Command += new CommandEventHandler(lnkColourAlternative_Click);
            //lnk.Click 
            li.Controls.Add(lnk);
            ul1.Controls.Add(li);
            listItemIds++;
        }
    }

    private void Clicked(object sender, EventArgs e)
    {
        var btn = sender as LinkButton;
        btn.Text = "Clicked";
    }



回答2:


Do this sort of thing OnInit and make sure you recreate the controls on every postback.

See this KB article for an example - a bit outdated but the methodology is still the same.



来源:https://stackoverflow.com/questions/9485907/dynamically-created-list-of-link-buttons-link-buttons-not-posting-back

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!