1

I have an ASP.NET WebForms page with several buttons added programmatically like this:

    private void AddExportButton(Control control, Action clickAction) {
        LinkButton exportButton = new LinkButton {
            Text = "Export",
            EnableViewState = false /*Buttons will be recreated on each Postback anyway.*/
        };
        exportButton.Click += (sender, e) => clickAction();
        control.Controls.Add(exportButton);
    }

Now this works, as long as the AddExportButton() method is called along the path from the OnLoad() or OnPreLoad() method. It does not fire the handler action however, when AddExportButton() called from the OnLoadComplete() method.

I would like to add/create the buttons also when another event handler (coming from a dropdown) gets called. This only happens after the OnLoad(), which will break my code.

Why is this, and how can I use anonymous methods as event handlers in this case?

See this nice cheat sheet about the ASP.NET Page LifeCycle by Léon Andrianarivony for more info about the order of the page/control creation.

Marcel
  • 15,039
  • 20
  • 92
  • 150

1 Answers1

1

In the page life cycle, the internal RaisePostBackEvent method (which raises the button's Click event) occurs between OnLoad and OnLoadComplete. If you wait until OnLoadComplete to add the LinkButton and hook up its Click event, then obviously the event won't be raised: it's too late.

(The fact that you're using an anonymous method is irrelevant.)

Can you add the export button in the .aspx but set its Visible property to false when you don't want it to appear?

Michael Liu
  • 52,147
  • 13
  • 117
  • 150
  • Hm, the problem for me is, that there are multiple export buttons to add (And I am doing some other, expensive, stuff, which I did not mention). As said, Depending on the user clicking on the mentioned dropdown on a certain tab control, I want to add a subset of those buttons only. Setting them to invisible is just much work for no relevant outcome. Thus, adding needs to be in reaction of another click event. I can not do earlier, since earlier, the click event of the tab was not handeled. Does that make sense? – Marcel Aug 13 '13 at 11:57
  • Can you post the code for the dropdown's event handler as well? (At least the part that adds the button.) – Michael Liu Aug 13 '13 at 13:57
  • That part is already shown, though this code is quite buried under many other calls. I have understood your answer and built it quite like that (Creating the button each time in the OnLoad(), and it works. All event handlers get called as expected, and the unwanted ones are not visible. – Marcel Aug 13 '13 at 14:16