Search code examples
c#asp.netvisual-studioevent-handlinglinkbutton

onClick for dynamically generated LinkButton


In my sharepoint web-part application. I am dynamically generating LinkButtons as below. and this works fine

foreach (var pName in productTypesNames[productType] )
{
   var subLi = new HtmlGenericControl("li");
   var linkButton = new LinkButton{ Text = pName };
   linkButton.Click += new EventHandler(linkButton_Click);
   subLi.Controls.Add(linkButton);
   ul.Controls.Add(subLi);
}

However, when I click on one of the links in UI, my debugger never hits the breakpoint that is set at very first line of

void linkButton_Click(object sender, EventArgs e)
{
}

More Code

protected void StateClicked(object sender, CommandEventArgs e)
{
  //Generate a dictionary of type Dictionary<string, List<string>>
  //Display the dictionary
  foreach (var productType in productTypesNames.Keys)
        {
            var li = new HtmlGenericControl("li");
            nav.Controls.Add(li);
            var ul = new HtmlGenericControl("ul");

            var anchor = new HtmlGenericControl("a");
            anchor.Attributes.Add("href", "#");

            foreach (var pName in productTypesNames[productType] )
            {
                var subLi = new HtmlGenericControl("li");
                var linkButton = new LinkButton{ Text = pName };
                linkButton.Click += new EventHandler(linkButton_Click);
                subLi.Controls.Add(linkButton);
                ul.Controls.Add(subLi);
            }
            anchor.InnerHtml = productType;
            li.Controls.Add(anchor);
            li.Controls.Add(ul);
        }
 }

Where stateClicked is called by a click on the image map of USA.


Solution

  • You probably aren't recreating the dynamically generated links on every postback.

    If you have a if (!IsPostback) wrapped around your foreach, try removing it.