Why do my buttons (array of buttons) disappear after I click any of them? Here is the code structure. Thanks a lot in advance.
public partial class Seatalloc2 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateControls();
}
}
protected void PopulateControls()
{
Button[,] buttonArray = new Button[10, 14];
for (int a = 0; a < 10; a++)
for (int b = 0; b < 14; b++)
{
buttonArray[a, b] = new Button();
Panel2.Controls.Add(buttonArray[a, b]);
}
}
public void buttonHandler(object sender, EventArgs e)
{
Button btn = sender as Button;
btn.BackColor = Color.Red;
}
}
If you look at my answer to your last question you will find an example addressing this issue:
https://stackoverflow.com/a/11061782/1268570
The root problem is understanding the ASP.Net page life-cycle (I hate it) but it is useful and crucial to understand the basics behind it
This documentation from Microsoft explains in detail the page life cycle
http://msdn.microsoft.com/en-us/library/ms178472.aspx
Basically the controls are disappearing because you need to re-create them again in the page with each postback, and in your code, you are only creating them the first time you load your page
The recommended event to create dynamic controls is the
PreInit
if you do not have a master page or theInit
if you do have one master pageSo if you change your code to:
Your buttons will conserve their state. Do not worry about the state, even when they are re-created in each post, since you are doing it in the
Init
event, ASP.Net will load theViewState
automatically to your controls (this is possible because ASP.Net loads the view state after theInit
event and before theLoad
event)As a quick reference take a look at the page life-cycle:
You must recreate dynamically created controls on every postback at the latest in Page_Load with the same ID as before to ensure that
ViewState
is loaded correctly and events are triggered. In your case with a static number of controls it's sufficient to callPopulateControls
even on postbacks:But you also need to add the
Buttons
to thePage
's control-collection, for example to aPanel
. Your array of buttons has no purpose: