Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic ImageButton click event not fired

Tags:

c#

asp.net

I have the following code:

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 { }
}

When I click on _btnRemoveEmpleado, the postback is executed but I never reach the string s = ""; line. How could I execute the _btnRemoveEmpleado_Click code, please?

like image 866
David Ortega Avatar asked May 17 '26 20:05

David Ortega


1 Answers

Remove the using, controls are disposed automatically by ASP.NET, they have to live until the end of the page's lifecycle. Apart from that create your dynamic control in Page_Init, then it should work.

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);
}
like image 157
Tim Schmelter Avatar answered May 20 '26 09:05

Tim Schmelter