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

Adding a user control to a page programatically while preserving controls already present(以编程方式将用户控件添加到页面,同时保留已存在的控件)
本文介绍了以编程方式将用户控件添加到页面,同时保留已存在的控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在运行时将用户控件添加到 div 中.我可以添加控件没有问题,但它会覆盖之前添加的控件.

I am trying to add a user control into a div at runtime. I can add the control no probelem but it overwrites the previous control added.

基本上,我正在尝试将乘客添加到旅行系统 - 乘客详细信息在用户控制中,我事先不知道会有多少.我有一个添加新乘客按钮,它应该将新用户控件附加到 div 中,而不会覆盖以前的乘客.

Basically, I am trying to add passengers to a travel system - the passenger details are in the user control and I don't know in advance how many there will be. I have an add new passenger button which should append the new user control into the div without overwriting the previous passenger.

代码是c#/.net 4.

The code is c#/.net 4.

我已尝试将控件数据保存到视图状态中并使用新的重新添加它,但这也不起作用.这是我正在使用的代码片段

I have tried to save the control data into viewstate and re add it with the new one but that also doesn't work. Here is a snippet of the code I'm using

foreach (Control uc in p_passengers.Controls) {
        Passenger p = uc as Passenger;
        if (p != null) {
            p.SaveValues();            
        }
    }

但是,p.SaveAs()(只是将控件值写入 ViewState)永远不会被命中.

however, p.SaveAs() (just writes the control values into ViewState) is never hit.

我确定这只是一些愚蠢的东西,但有什么想法吗??

Im sure its just something stupid but any ideas??

大家好.

推荐答案

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

请记住,每个回发都是 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);
       }
  }

这篇关于以编程方式将用户控件添加到页面,同时保留已存在的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)