Puppy
Puppy

Reputation: 146900

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);

Upvotes: 2

Views: 241

Answers (1)

Jakub Linhart
Jakub Linhart

Reputation: 4072

Dynamically added buttons must be created on every request, most likely it is sufficient before raising postback events (e.g. 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.

Upvotes: 1

Related Questions