Dynamically created list of link buttons, link buttons not sending back

Hi I am dynamically creating link buttons in the list of "ul li". Then I try to associate each link button with a click event, where I set a label in the link button text. however, the event that should fire does not fire?

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 in if (! page.ispostback), and the label text is never set anywhere. heres to the event

 protected void Clicked(object sender, EventArgs e) { LinkButton lno = sender as LinkButton; litSelectedColour.Text = lno.Text; } 
+4
source share
2 answers

The code should run on every 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"; } 
+5
source

Do such an OnInit thing and make sure you recreate the controls with every postback.

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

+1
source

Source: https://habr.com/ru/post/1398852/


All Articles