Dynamically generated buttons, on click not being executed

I need to generate a dynamic list of buttons, I already did, with an event handler attached to it.

However the event handler is not being executed.

private void GetOptions(EcoBonusRequest request)
        {
            var ecobonuswworkflow = WorkflowFactory.CreateEcobonusWorkflow();
            ecobonuswworkflow.SetCurrentStep(request.CurrentStatus);
            var currentoptions = ecobonuswworkflow.GetCurrentOptions();
            foreach(var option in currentoptions)
            {
                var btn = new Button() {Text = option.OptionName};
                btn.Click +=new EventHandler(btn_Click);
                Buttons.Controls.Add(btn);
            }

        }


        void btn_Click(object sender, EventArgs e)
        {
            var btn = (Button) sender;
            string command = btn.Text;
            EcoBonusRequest request = this.GetDBRequest(RequestBaseId.Value);
            EcoBonusRequestBL.AddWorkflowHistoryItem(request, command,CurrentUser, command);
        }

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The controls that you add dynamically in your page must be added in Page_init event, and they must have unique Ids. If you are adding textboxes or some other controls where user can input or change value, than on every post back when these controls are re-added they must have same IDs.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply