简体   繁体   中英

C# / apsx.net - Dynamically created button doesn't work

Here is my problem: I had dynamically created some buttons in my page (in the Page_PreInit method), all linked to the same event handler. But those buttons don't fire the event when I click on them... Can someone help me?

Here is some of my code:

Button creation (on a foreach loop on the Page_PreInit method):

Button b = new Button();
field.Controls.Add(b);

b.Text = "Download";
b.ID = tmp_out[type] as String;
b.Click += new EventHandler(Download_Click);

The OnClick method:

private void Download_Click(object sender, EventArgs e)
{
    //doing some stuff
}

Dynamic controls must be added during Page PreInit or Init, not on load. This is because of page lifecycle and viewstate loading... so try that first to see if that solves the problem.

Also, I believe I read that it's best to order your code this way:

Button b = new Button();
field.Controls.Add(b);

b.Text = "Download";
b.ID = tmp_out[type] as String;
b.Click += new EventHandler(Download_Click);

Adding the control first to the inner collection, then changing it's properties.

your event handler statement is

b.Click += new EventHandler(Download_Click);

but your method is

private void Download_Command(object sender, CommandEventArgs e)

are you sure its the right method to be triggered?

Should not be like this?

...
b.Click += new EventHandler(Download_Command);
...

private void Download_Command(object sender, EventArgs e)
{
    //doing some stuff
}

Ok I solved my problem.

The ids of the buttons was containing some '\\'. I just removed those '\\' and it works just fine.

Thanks all for your reply!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM