简体   繁体   中英

Can't add programmatic controls in ASP.NET

I've got a page in ASP.NET, and I'm dynamically adding a subclass of WebControls.Button to the Controls data member of a pre-existing static TableCell. The button displays fine in the browser as expected. But when I click the button, the event handler I added for button.Click is not being called. Any suggestions as to why this is?

var controls = this.displaytable.Rows[i].Cells[j].Controls;
var button = new TableButton(j, i);
button.Click += new EventHandler(this.button_Click);
button.UseSubmitBehavior = false;
button.Text = "Available";
controls.Add(button);

Dynamically added buttons must be created on every request, most likely it is sufficient before raising postback events (eg OnLoad). Button needs to have an explicit ID sometime:

var controls = this.displaytable.Rows[i].Cells[j].Controls;
var button = new TableButton(j, i);
button.Click += new EventHandler(this.button_Click);
button.UseSubmitBehavior = false;
button.Text = "Available";
button.Id = string.Format("TableButton_{0}_{1}", j, i);
controls.Add(button);

This SO answer may help little bit: ASP.NET dynamic Command Button event not firing .

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