Having published a dnj article on events in asp.net I got presented with the following problem :
The webform has an emty label and an empty table. At runtime the table is populated with a collection of imagebuttons. Every imagebutton will get an eventhandler.
private void buildTable(int rows, int cols)
{
for (int i =0; i < rows; i++)
{
TableRow tr = new TableRow();
for (int j = 0; j < cols; j++)
{
TableCell tc = new TableCell();
ImageButton ib = new ImageButton();
ib.ToolTip = string.Format("This is button {0} {1}", i, j);
ib.Click+=new ImageClickEventHandler(ib_Click);
tc.Controls.Add(ib);
tr.Cells.Add(tc);
}
Table1.Rows.Add(tr);
}
}
The method is quite straigthforward. It creates table rows, table cells and adds an imagebutton to every cell. The same eventhandler is used for all buttons
private void ib_Click(object sender, ImageClickEventArgs e)
{
ImageButton ib = sender as ImageButton;
Label1.Text = string.Format("ToolTip: {0} X : {1} Y : {2}", ib.ToolTip, e.X, e.Y);
}
Running the code the label will display which button was clicked. For the details you are invited to the original article.
The important part is the moment in the page life cycle the eventhandler is assigned. If the buildTable method is called from the page_load the event handler will work. If it is called in the pre-render the table will be populated but the eventhandlers will not fire. At that moment in the page life cycle the wire-up of events is allready set and fixed.
Peter