動態建立ASP.NET控制項並保持其狀態分析及實現

來源:互聯網
上載者:User

動態建立asp.net控制項並儲存其狀態,簡要總結如下:
1:背景知識:需要瞭解Page的生存周期。
2:方法總結:
1>
在頁面代碼檔案中的聲明地區寫(這裡以Label控制項為例):
Label x = new Label();
pageload事件中代碼為:
protected void Page_Load(object sender, EventArgs e)
{
    this.Page.Controls.Add(x);
}
在頁面需要設定x值時寫: x.Text = "zzz";等等。如此,無論頁面如何重新整理,即可實現動態建立控制項並儲存狀態目的。

2>
思路:將控制項動態添加到頁面已有的控制項或者控制項容器中去,然後根據需要動態設定其狀態即可。
例如:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
                          <ItemTemplate>
                            <asp:Literal ID="tr" runat="server"></asp:Literal>
                        </ItemTemplate>                   
</asp:Repeater>
在Repeater1_ItemDataBound事件中寫:(e.Item.FindControl("ds") as Literal).Text = "";

兩種思路相通之處:控制項一旦被添加到頁的控制項樹裡,TrackViewState()方法就負責跟蹤其狀態。只要控制項被添加到控制項樹裡,這個方法就會被自動的觸發。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.