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 the Init
if you do have one master page
So if you change your code to:
void Page_Init(object sender, EventArgs e)
{
PopulateControls();
}
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 the ViewState
automatically to your controls (this is possible because ASP.Net loads the view state after the Init
event and before the Load
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 call PopulateControls
even on postbacks:
protected void Page_Load(object sender, EventArgs e)
{
PopulateControls();
}
But you also need to add the Buttons
to the Page
's control-collection, for example to a Panel
. Your array of buttons has no purpose:
protected void PopulateControls()
{
for (int a = 0; a < 10; a++)
for (int b = 0; b < 14; b++)
{
var btn = new Button();
btn.ID = "Btn_" + a + "_" + b;
// add an event handler for the click-event
btn.Click += buttonHandler;
MyButtonPanel.Controls.Add(btn);
}
}