How to call the`Onclick` event in code Behind?

Asked

Viewed 1,097 times

0

How can I call the event OnClick in the code behind of a dynamically created button?

I’m trying it the way down, but I’m not getting it.

void MontarHtml(List<DocumentoImagens> DocImagens)
{
    foreach (DocumentoImagens DocImg in DocImagens)
    {
        TableRow trTesto = new TableRow();
        trTesto.Cells.Add(MontarTextBox(DocImg));
        trTesto.CssClass = "textarea";
        Table1.Rows.Add(trTesto);

        TableRow trimagem = new TableRow();

        TableCell tdckb = new TableCell();

        ImageButton btn = new ImageButton { ID = DocImg.IdDocImagem.ToString() };
        btn.ImageUrl = "~/Imagens/Icons/delete.gif";
        btn.Click += new ImageClickEventHandler(butDeleteImagem_Click);
        tdckb.Controls.Add(btn);
        trimagem.Cells.Add(tdckb);
        Table1.Rows.Add(trimagem);

        TableCell tdig = new TableCell();
        Image ig = new Image();
        ig.ImageUrl = DocImg.Url;
        ig.ID = "idimg" + DocImg.IdDocImagem.ToString();
        ig.CssClass = "image";
        tdig.Controls.Add(ig);
        trimagem.Cells.Add(tdig);
        Table1.Rows.Add(trimagem);
    }
}

protected void butDeleteImagem_Click(object sender, ImageClickEventArgs e)
{
    try
    {
        ImageButton Btn = sender as ImageButton;
        if (Btn != null)
        {
            Int32 IdDocImagem = Convert.ToInt32(Btn.ID);

            new DocumentoImagensBusiness().DeleteDocumentoImagens(IdDocImagem);
        }

        var DocuImagens = new DocumentoImagensBusiness().GetDocumentoImagens(_documento.IdDocumento);
        Table1.Controls.Clear();
        LoadImagens(DocuImagens);
    }
    catch (Exception ex)
    {
        //...
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        var DocuImagens = new DocumentoImagensBusiness().GetDocumentoImagens(_documento.IdDocumento);
        LoadImagens(DocuImagens);

        //..............
    }
    catch (Exception ex)
    {
       //..
    }
}

private void LoadImagens(List<DocumentoImagens> DocuImagens)
{
    if (DocuImagens != null)
        MontarHtml(DocuImagens);

    //.....................
}

1 answer

3


Try it like this

btn.Click += new ImageClickEventHandler(butDeleteImagem_Click);

Put this code on PageLoad() of your page.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.