中继器和自定义控件 – 动态添加到集合和保留值

自从我使用Web Forms以来,我发现自己并没有记住大部分的特权。

我有一个用户控件,它有一个按钮,一个转发器和转发器的ItemTemplate属性是另一个用户控件。

 

我们的想法是,当用户单击“添加”按钮时,会向集合中添加一个新的ucRequest实例。 背后的代码如下:

 public partial class ucRequests : UserControl { public List requests { get { return (from RepeaterItem item in rptrRequests.Items select (ucRequest) (item.Controls[1]) ).ToList(); } set { rptrRequests.DataSource = value; rptrRequests.DataBind(); } } protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; requests = new List(); } protected void btnAdd_Click(object sender, EventArgs e) { var reqs = requests; reqs.Add(new ucRequest()); requests = reqs; } } 

经过大量的谷歌搜索后,我现在记得我应该在OnInit方法中绑定Repeater,以便ViewState在usRequest控件中将控件的捕获数据放在post backs之间但是当我尝试这样做时我会一直有Repeater上的单个控件实例,因为其Items集合始终为空。

我怎么能设法做到这一点?

提前致谢。

您只需要在视图状态中控制ID,而不是整个控件集合。

在此处输入图像描述

 <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ucRequests.ascx.cs" Inherits="RepeaterWebApplication.ucRequests" %>  
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ucRequest.ascx.cs" Inherits="RepeaterWebApplication.ucRequest" %> private List _controlIds; private List ControlIds { get { if (_controlIds == null) { if (ViewState["ControlIds"] != null) _controlIds = (List) ViewState["ControlIds"]; else _controlIds = new List(); } return _controlIds; } set { ViewState["ControlIds"] = value; } } protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { foreach (int id in ControlIds) { Control ctrl = Page.LoadControl("ucRequest.ascx"); ctrl.ID = id.ToString(); PlaceHolder1.Controls.Add(ctrl); } } } protected void btnAdd_Click(object sender, EventArgs e) { var reqs = ControlIds; int id = ControlIds.Count + 1; reqs.Add(id); ControlIds = reqs; Control ctrl = Page.LoadControl("ucRequest.ascx"); ctrl.ID = id.ToString(); PlaceHolder1.Controls.Add(ctrl); }

尝试在OnItemDatabound事件期间获取ucRequests,此时您可以编辑转发器的itemtemplate的内容。 单击添加按钮导致回发后,您可以到达那里。 这是一个类似场景的示例