Button array disappears after click event

前端 未结 2 1159
刺人心
刺人心 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: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);
        }
    }
    

提交回复
热议问题