添加一个用户控件的网页编程,而preserving控制已经present [英] Adding a user control to a page programatically while preserving controls already present
问题描述
我想在运行时添加用户控件到一个div。我可以添加控件没有probelem但它覆盖previous控制补充说。
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.
基本上,我想乘客添加到行驶系统 - 乘客细节都在用户的控制和我事先不知道有多少会出现。我有一个新的添加按钮的乘客应追加新的用户控件到格但不覆盖previous乘客。
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.
在code是C#/。NET 4.
The code is c#/.net 4.
我试图挽救控制数据到视图状态,并重新用新的补充,但也不能正常工作。下面是我使用的code的片段
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类,你pviously创建需要$ P $显式地重新创建任何控件的新实例。
Remember each postback is a new instance of the Page class and any controls you previously created will need to be explicitly re-created.
更新
如果你不得不在ViewState中添加的项目列表,像这样..
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");
}
protected overrides CreateChildControls()
{
foreach (string item in this.Items)
{
Passanger p = new Passenger();
p.Something = item;
this.p_passengers.Controls.Add(p);
}
}
这篇关于添加一个用户控件的网页编程,而preserving控制已经present的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!