Button array disappears after click event

前端 未结 2 1160
刺人心
刺人心 2021-01-24 12:30

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 :          


        
相关标签:
2条回答
  • 2021-01-24 12:43

    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:

    enter image description here

    0 讨论(0)
  • 2021-01-24 12:49

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题