asp:Button Click event not being fired

2019-02-27 05:41发布

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?

2条回答
倾城 Initia
2楼-- · 2019-02-27 05:59

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.

查看更多
爷、活的狠高调
3楼-- · 2019-02-27 06:08

@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.

查看更多
登录 后发表回答