0

I have a button created in code behind like so:

some method {
    Button btnExportToExcel = new Button();
    btnExportToExcel.Text = "Export To Excel";
    btnExportToExcel.Click += new EventHandler(btnExportToExcel_Click);
    pnlListView.Controls.Add(btnExportToExcel);
}

protected void btnExportToExcel_Click(object sender, EventArgs e)
        {
            //do something
        }

The problem is that I can't ever get to execute the code from the event method.

Why is that?

1
  • When is Somethod called? Dinamic controls should be added in PreInit event Commented Feb 13, 2014 at 14:21

3 Answers 3

2

are you adding controls to page in preinit event handler? Check

Sign up to request clarification or add additional context in comments.

3 Comments

It is loaded in the Page_Load method and inside an if (!IsPostBack) statament
Ok loading it in Pre_Init fixes the issue. Thank you.
There is another small issue, what if I want to add the button control after other controls which get conditionally created? Meaning they might exist at pre_init
1

You must add the button to any controler .

 protected void Page_Load(object sender, EventArgs e)
    {
        Button btnExportToExcel = new Button();
        btnExportToExcel.Text = "Export To Excel";
        btnExportToExcel.Click += new EventHandler(btnExportToExcel_Click);
        //this is add the button to the form1
        this.form1.Controls.Add(btnExportToExcel);
    }

    void btnExportToExcel_Click(object sender, EventArgs e)
    {
        //...
        Response.Write("click me...");
    }

1 Comment

Sorry I am adding it to a panel. Edited the code above.
0

Please add the dynamic controls in the Page's Init event handler so that the ViewState and Events are triggered appropriately.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.