C# ImageButton Click event not fired

ε祈祈猫儿з 提交于 2021-01-28 05:52:06

问题


Code first:

public class ExtendedGridView : GridView
{
    private ImageButton m_btnPrint;
    public ImageButton PrintButton
    {
        get { return m_btnPrint; }
        set { m_btnPrint = value; }
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        PrintButton = new ImageButton();
        PrintButton.Click += new ImageClickEventHandler(OnPrintButtonClick);
        PrintButton.AlternateText = "Print";
        PrintButton.ImageUrl = "../../Images/Print.png";

        TableCell cell = new TableCell();
        cell.Controls.Add(PrintButton);
        cell.ColumnSpan = this.FooterRow.Cells.Count;

        this.FooterRow.Cells.Clear();
        this.FooterRow.Cells.Add(cell);
    }

    public void OnPrintButtonClick(object sender, ImageClickEventArgs e)
    {
        // Do Stuff
    }
}

This bit of code is intended to replace the footer content with an image button, and it does this fine. The plan is to handle the click event in the same class but I can't get the method 'OnPrintButtonClick' to go, it just won't break there. The page does, however, seem to be doing a post back. There have been questions on this before on this site but I haven't seen an answer yet. Thanks in advance


回答1:


This is a page lifecycle problem.

You're adding the ImageButton to the page (and registering your handler) during the PreRender phase, which occurs after control events have been dispatched. Therefore, your handler will never be called.

Try adding the button during the Load phase, if at all possible.



来源:https://stackoverflow.com/questions/6762696/c-sharp-imagebutton-click-event-not-fired

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!