Question

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.

Was it helpful?

Solution

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top