且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以编程方式将用户控件添加到页面,同时保留已存在的控件

更新时间:2023-02-11 16:58:39

你是在 重新创建所有每次回发的动态控件?

请记住,每个回发都是 Page 类的新实例,您之前创建的任何控件都需要显式重新创建.

Remember each postback is a new instance of the Page class and any controls you previously created will need to be explicitly re-created.

更新

如果您在视图状态中有一个已添加项目的列表,类似这样..

If you had a list of added items in viewstate, something like this..

    private List<string> Items
    {
         get
         {
              return ViewState["Items"] = (ViewState["Items"] ?? new List<string>());
         }
    }

然后在您的点击处理程序中,您可以简单地添加到此列表中:

Then in your click handler you could simply add to this list :

   private void btn_Click(object sender, EventArgs e)
   {
        this.Items.Add("Another Item");
   }

然后覆盖 CreateChildControls

  protected overrides CreateChildControls()
  {
       foreach (string item in this.Items)
       {
            Passanger p = new Passenger();
            p.Something = item;
            this.p_passengers.Controls.Add(p);
       }
  }