问题
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