3

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?

DavidG
  • 113,891
  • 12
  • 217
  • 223
  • Did you set `AutoPostBack = true` on the button? – DavidG Dec 15 '15 at 09:39
  • When you say "I never reach the string s", do you mean when you debug you are getting into void _btnRemoveEmpLeado_Click but only going into the catch and finally blocks? – sr28 Dec 15 '15 at 09:40
  • 1
    Do not use `using` block for the `ImageButton`. As the button is disposed after the `using` block, it won't be able to handle events. Check this: http://stackoverflow.com/questions/21316266/event-handler-stops-working-after-dispose – mshsayem Dec 15 '15 at 09:41
  • DavidG, ImageButton doesn't contain a definition of "AutoPostBack" so it's not possible. – David Ortega Dec 15 '15 at 09:44
  • sr28, No, the _btnRemoveEmpleado_Click code is not executed. – David Ortega Dec 15 '15 at 09:45

1 Answers1

4

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);
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939