2

I am dynamically adding rows in an asp table. In each row of the table I am also including a button which has a SelectProduct_Click event.

The problem is that even though I am registering the click event, the event is not being fired.

The button is being added in this way:

btnSelect = new Button();
btnSelect.ID = "btnSelect";
btnSelect.CommandArgument = od.ProductId;
btnSelect.Click += new EventHandler(this.SelectProduct_Click);
btnSelect.CssClass = "button";
btnSelect.Text = "Select";
cell = new TableCell();
cell.Controls.Add(btnSelect);
row.Cells.Add(cell);

How can I get my button to fire on click?

MaxPRafferty
  • 4,819
  • 4
  • 32
  • 39
user1137243
  • 51
  • 2
  • 6

2 Answers2

3

You need to learn about the ASP.NET page lifecycle.

In order for dynamic controls to fire their events on postback, they need to be recreated and attached to the event handler again.

The best place to create (and re-create) dynamic controls is in the OnInit event handler.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

@Oded - you are absolutely right about the right timing to add dynamic controls. However it is not written on which event he is trying to add the button.

Veronica
  • 242
  • 1
  • 3
  • Sorry I forgot to mention it. I am adding the button in a method which is called when the user clicks on a particular button named Show List. As I need that the buttons are created after the user clicks the Show List button I'm not sure if I can call such method (which creates the buttons) in the OnInit section. – user1137243 Jan 08 '12 at 16:51
  • Thanks for clarification. Couldn't you create the button in the OnInit event but hide it. Then when the Show List button is clicked just show the hidden button. :/ – Veronica Jan 08 '12 at 16:56
  • Thanks for your help, I will use a gridview and use the gridviews's select record button instead.. as I needed the button to select a certain record. – user1137243 Jan 08 '12 at 17:27