动态创建的ImageButton点击事件未被触发

3
我有以下代码:
protected void Page_Load(object sender, EventArgs e)
{
    using (ImageButton _btnRemoveEmpleado = new ImageButton())
    {
        _btnRemoveEmpleado.ID = "btnOffice_1";
        _btnRemoveEmpleado.CommandArgument = Guid.NewGuid().ToString();
        _btnRemoveEmpleado.Height = 15;
        _btnRemoveEmpleado.Width = 15;
        _btnRemoveEmpleado.ImageUrl = "cross-icon.png";
        _btnRemoveEmpleado.Click += new ImageClickEventHandler(_btnRemoveEmpleado_Click);

        this.phPartesPersonal.Controls.Add(_btnRemoveEmpleado);
    }
}

void _btnRemoveEmpleado_Click(object sender, ImageClickEventArgs e)
{
    try
    {
        string s = "";
    }
    catch (Exception ex)
    {
    }
    finally { }
}

当我点击 _btnRemoveEmpleado 时,会执行 postback 但永远不会到达 string s = ""; 这一行。请问如何执行 _btnRemoveEmpleado_Click 的代码?

你在按钮上设置了 AutoPostBack = true 吗? - DavidG
当你说“我从未到达字符串s”时,你是指在调试时进入了void _btnRemoveEmpLeado_Click,但只进入了catch和finally块吗? - sr28
1
不要在 ImageButton 中使用 using 块。因为在 using 块之后,该按钮将被处理,无法处理事件。请参考:http://stackoverflow.com/questions/21316266/event-handler-stops-working-after-dispose - mshsayem
DavidG,ImageButton不包含“AutoPostBack”的定义,因此不可能实现。 - David Ortega
sr28,不,_btnRemoveEmpleado_Click代码没有被执行。 - David Ortega
1个回答

4

移除using语句,ASP.NET会自动处理控件的释放,在页面生命周期结束之前它们必须存在。此外,在Page_Init中创建动态控件,这样就可以正常工作。

protected void Page_Init(object sender, EventArgs e)
{
     ImageButton _btnRemoveEmpleado = new ImageButton();
    _btnRemoveEmpleado.ID = "btnOffice_1";
    _btnRemoveEmpleado.CommandArgument = Guid.NewGuid().ToString();
    _btnRemoveEmpleado.Height = 15;
    _btnRemoveEmpleado.Width = 15;
    _btnRemoveEmpleado.ImageUrl = "cross-icon.png";
    _btnRemoveEmpleado.Click += new ImageClickEventHandler(_btnRemoveEmpleado_Click);

    this.phPartesPersonal.Controls.Add(_btnRemoveEmpleado);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接