Click to See Complete Forum and Search --> : custom control problems


mark reed
March 14th, 2005, 05:47 AM
I have a custom control which has 'n' buttons on it. n will be set at run time.

Each of the buttons should have an event handler. My problem is that I cannot get the event handers to work for the buttons that I dynamically create.

My code for the custom control is as follows:

public class WebCustomControl1 : System.Web.UI.WebControls.WebControl
{
private int numOfButtons;

protected override void Render(HtmlTextWriter writer)
{
//draw a table with NumOfButtons columns.
//in each column add a new button with an event handler.
AddAttributesToRender(writer);
writer.RenderBeginTag(HtmlTextWriterTag.Table); //start the HTLM table
writer.RenderBeginTag(HtmlTextWriterTag.Tr);

for (int i=0; i<numOfButtons; i++)
{
writer.RenderBeginTag(HtmlTextWriterTag.Td);
Button b = new Button();
b.Text = "a button";
b.Click += new EventHandler(OnButtonclick);
b.RenderControl(writer);
Controls.Add(b);
writer.RenderEndTag(); //end the td
}

writer.RenderEndTag(); //end the tr
writer.RenderEndTag(); //end the HTML table
}

private void OnButtonclick(object o, EventArgs ea)
{
Button b = (Button)o;
b.Text = "clicked";
}
}

This code displays n buttons in a table as expected, but the event handler is not called when I click on the button?

Anyone know what i am doing wrong?

Thanks in advance.