2013-01-21 23 views
0

自從我使用Web窗體以來,我一直都沒有記住大部分特權。直放站和自定義控制 - 動態添加到收集和保留值

我有一個用戶控件,它有一個按鈕,一箇中繼器,中繼器的ItemTemplate屬性是另一個用戶控件。

<asp:Button runat="server" ID="btnAdd" CssClass="btn" Text="Add" OnClick="btnAdd_Click"/> 
<br/> 
<asp:Repeater runat="server" ID="rptrRequests"> 
    <ItemTemplate> 
     <uc1:ucRequest ID="ucNewRequest" runat="server" /> 
    </ItemTemplate> 
</asp:Repeater> 

這個想法是,當用戶點擊添加按鈕時,一個新的ucRequest實例被添加到集合中。後面的代碼如下:

public partial class ucRequests : UserControl 
{ 
    public List<ucRequest> 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<ucRequest>(); 
    } 

    protected void btnAdd_Click(object sender, EventArgs e) 
    { 
     var reqs = requests; 
     reqs.Add(new ucRequest()); 
     requests = reqs; 
    } 
} 

經過一番google搜索我現在想起來,我應該結合在OnInit方法中的中繼器,以便ViewState的把控制的捕獲數據的ucRequest控制範圍內對他們在回發之間,但當我嘗試這樣做時,我總是會在Repeater上擁有一個單一的控件實例,因爲它的Items集合總是空的。

我怎麼能做到這一點?

在此先感謝。

回答

0

你只需要在視圖狀態下控制ID代替整個控制集合。

enter image description here

<%@ Control Language="C#" AutoEventWireup="true" 
    CodeBehind="ucRequests.ascx.cs" 
    Inherits="RepeaterWebApplication.ucRequests" %> 
<asp:Button runat="server" ID="btnAdd" CssClass="btn" Text="Add" 
    OnClick="btnAdd_Click" /> 
<br /><asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder> 

<%@ Control Language="C#" AutoEventWireup="true" 
    CodeBehind="ucRequest.ascx.cs" 
    Inherits="RepeaterWebApplication.ucRequest" %> 
<asp:TextBox runat="server" ID="TextBox1"></asp:TextBox> 

private List<int> _controlIds; 

private List<int> ControlIds 
{ 
    get 
    { 
     if (_controlIds == null) 
     { 
      if (ViewState["ControlIds"] != null) 
       _controlIds = (List<int>) ViewState["ControlIds"]; 
      else 
       _controlIds = new List<int>(); 
     } 
     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); 
} 
+0

哇!有用!我不知道你可以做這種事情。這使它變得如此簡單。謝謝! –

0

嘗試在OnItemDatabound事件期間獲取ucRequests,此時您可以編輯轉發器的itemtemplate的內容。點擊添加按鈕導致回發後,您可以到達那裏。 Here's a sample with a similar scenario