简体   繁体   中英

ASP.NET dynamic button creation with event handler

I have a ASP.NET web form and I am generating a button dynamically. If the button is clicked, I want it redirected to a new page but it doesn't work. Here is what my Page_Load event and event handler look like

Below is a sample code snippet

protected void Page_Load(object sender, EventArgs e)
{
    Button editBtn = new Button();
    editBtn.Text = "Edit";
    editBtn.ID = i.ToString();
    editBtn.Command += MyBtnClick;

    TableRow row = new TableRow();
    TableCell cell1 = new TableCell();

        cell1.Controls.Add(editBtn);
    row.Cells.Add(cell1);

    Table1.Rows.Add(row);

}

private void MyBtnClick(object sender, EventArgs e)
{
    Button btn = (Button)sender;

    Response.BufferOutput = true;
    Response.Redirect(~/NextPage.aspx); 
}

Why is that the event handler is not fired?

Thanks

要将按钮单击委派给MyButton,请使用以下命令:

editBtn.Click += new EventHandler(MyBtnClick);

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