我有一个“添加控制按钮”,它为用户控件添加了一个预配置的ListBox。 (想法是添加UserControls,就像用户需要的那样多。)到目前为止一直很好。当我在ListBox中标记一个元素时,选择在第一次回发后丢失(例如在单击添加控制按钮之后)。看起来是一个生命周期问题,不知道。我的错误解决方案(根据我在网上找到的解决方案)如下:我使用List来恢复基于其ID的每个用户控件。谢谢。这是代码:
protected List<string> ControlsList
{
get
{
if (ViewState["controls"] == null)
{
ViewState["controls"] = new List<string>();
}
return (List<string>)ViewState["controls"];
}
}
//Restore Controls based on IDs in ControlsList
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
foreach (string contrID in ControlsList)
{
Control c;
c = LoadControl("v1.ascx");
c.ID = "v1-" + contrID;
PlaceHolder1.Controls.Add(c);
}
//Button Click adds Control
protected void addControl(object sender, EventArgs e)
{
Control c;
c = LoadControl("v1.ascx");
c.ID = "v1-" + NextID.ToString();
ControlsList.Add(c.ID);
PlaceHolder1.Controls.Add(c);
}
这里是用户控件:
public partial class v1 : System.Web.UI.UserControl
{
protected void Page_Init(object sender, EventArgs e)
{
v1_ListBox1.DataSourceID = "A1Vm1_SqlDataSource";
v1_ListBox1.DataTextField = "Vm1";
v1_ListBox1.DataValueField = "Vm1";
v1_ListBox1.SelectionMode = ListSelectionMode.Multiple;
}
答案 0 :(得分:1)
您应该更改ViewState的保存方式
protected override object SaveViewState()
{
var a = this.ControlsList;
var b = base.SaveViewState();
if (a.Count == 0 && b == null)
return null;
return new System.Web.UI.Pair(a, b);
}
protected override void LoadViewState(object savedState)
{
if (savedState == null)
return;
var pair = (System.Web.UI.Pair)savedState;
if (pair.First != null)
{
foreach (var id in (IList<string>)pair.First)
{
// add the control
}
}
if (pair.Second != null)
base.LoadViewState(pair.Second);
}
此方法将允许您首先初始化子控件,然后为它们加载视图状态。
您可能还想将ViewStateModeByIdAttribute添加到此控件中,该控件将动态添加控件,以便在您开始删除控件后,viewstate的加载不会失败。