Adding dynamic controls to the page is a tricky matter. Unfortunately, you cannot just declare an object of WebControl
derived type and expect it to work.
In ASP.NET WebForms, there is a concept called Page Lifecycle. It is a broad matter, but my point is that there is a particular order you must obey to plug-in the dynamic control into the page. A practical example follows.
Start with dynamic control declaration at the class level.
protected ImageButton imb = null;
Then you initialize it durring the page initialization. One possibility is to handle the PreInit event.
protected void Page_PreInit(object sender, EventArgs e)
{
imb = new ImageButton()
{
ID = "ID",
ImageUrl = "link to image"
};
imb.Click += Imb_Click;
Panel1.Controls.Add(imb);
}
private void Imb_Click(object sender, ImageClickEventArgs e)
{
// Do your stuff
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set initial properties as appropriate. E.g.
imb.AlternateText = "...";
}
}
You're good to go.