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

后端 未结 2 2039
庸人自扰
庸人自扰 2021-01-03 04:44

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

相关标签:
2条回答
  • 2021-01-03 05:24

    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";
        }
    
    0 讨论(0)
  • 2021-01-03 05:35

    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.

    0 讨论(0)
提交回复
热议问题