Reputation: 6405
I add a dynamic LinkButton in the UserControl. On postback, the dynamic control is displayed but the Controls collection is length 0.
namespace TestUC1
{
public partial class UC : System.Web.UI.UserControl
{
public event EventHandler Click;
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
foreach (Control c in Controls)
{
if (c is LinkButton)
{
((LinkButton)c).Click += new EventHandler(OnClick);
}
}
} else
{
AddNewButton();
}
}
protected void AddNewButton()
{
LinkButton lb = new LinkButton();
lb.ID = "TestLink";
lb.Text = "Test Link";
lb.Click += new EventHandler(OnClick);
Controls.Add(lb);
}
protected void OnClick(object sender, EventArgs e)
{
if (Click != null)
{
Click(this, new EventArgs());
}
}
}
}
Upvotes: 0
Views: 855
Reputation: 220
If you're dynamically adding controls then you will need to add the control both when Page.IsPostback=true, as well as when Page.IsPostback=false...
In other words, the following should do the trick for you:
protected void Page_Load(object sender, EventArgs e)
{
AddNewButton();
}
Another way to put it is that you as the programmer need to manually get the control tree back to what it was prior to the postback. Once you've done that the asp.net web forms "machinery" will load the viewstate and post data to get the controls back to state they were in prior to postback (and then raise events such as button clicks).
You may find the following references useful to help your understanding:
http://fuchangmiao.blogspot.co.uk/2007/11/aspnet-20-page-lifecycle.html
http://www.c-sharpcorner.com/uploadfile/61b832/Asp-Net-page-life-cycle-events/
Upvotes: 2