[英]Insert dynamic controls after page_load (ViewState persistent)
我有一個頁面,我在其中創建了一個動態表,其中包含引發事件的動態控件。 它有效,但我不想在某些事件中(因此在 page_load 之后)重新生成該表來打印表修改。
我理解這個問題,此時,我的控件沒有保留在視圖狀態中,因為它們是在 page_load 之后創建的,並且沒有引發它們的事件。 但我怎么能這樣做呢?
這是我的代碼:
protected void Page_Load(object sender, EventArgs e)
{
generateTable(); // When pass just here, it works well
}
private void generateTable()
{
Table tbl = new Table();
// Here I create my table with controls
tableContainer.Controls.Clear(); // tableContainer is a Panel fixed in aspx page
tableContainer.Controls.Add(tbl);
}
protected void txt_TextChanged(object sender, EventArgs e)
{
// Do some stuff to change values in the table
generateTable(); // Re-generate (but events will not be raised)
}
更新1:
我想過一些事情(這使我的開發復雜化),但我應該做 generateTable,它創建我所有的行和控件並在每個 page_load 上調用它。 另一方面,創建另一種填充控件的方法? 所以在事件中,我稱之為第二個。
但是我的表是動態生成的,並且也可以在事件之后添加控件(我有一個下拉列表,它在表中創建了一個新行和控件,所以我也被卡在這里,因為我不會在第一個看到該行回發?)
這是一個描述動態添加控件管理的非常好的鏈接: https : //web.archive.org/web/20050321094957/http : //devcenter.infragistics.com/Articles/ArticleTemplate.ASPX?ArticleID=2149
請注意,一旦您在 ASP.NET 后端的任何地方添加控件,您必須設置屬性
ViewState["AddedControl"] = "true";
此外,在回發期間,您的頁面將重新生成,因此屆時您必須重新創建控件並設置舊值。
從同一個鏈接:
public void Page_Load() {
if (IsPostBack) {
if (ViewState["AddedControl"] != null) {
// Re-create the control but do not
// restore settings configured outside
// the proc (i.e., MaxLength and BackColor)
TextBox t = AddTextBox();
}
}
}
public void OnClick(object sender, EventArgs e) {
TextBox t = AddTextBox();
// Modify properties outside the proc to
// simulate generic changed to the
// control's view state
t.MaxLength = 5;
t.BackColor = Color.Yellow;
}
public TextBox AddTextBox() {
TextBox ctl = new TextBox();
ctl.Text = "Hello";
placeHolder.Controls.Add(ctl);
// Records that a dynamic control has been added
ViewState["AddedControl"] = "true";
return ctl;
}
您應該改為在 PageInit 事件上生成控件。 在 PageInit 上生成的控件由 asp.net 框架自動管理(您將獲得視圖狀態持久性、引發的事件等...)
只是一個旁注:在您的 PageInit 上,您必須始終重新生成動態控件,否則框架將無法管理它們。
嘗試在 PageInit 上生成控件,然后在回發事件上更改它們的屬性,如下所示:
List<LiteralControl> list = new List<LiteralControl>();
protected void Page_Init(object sender, EventArgs e)
{
generateTable(); // When pass just here, it works well
}
private void generateTable()
{
Table tbl = new Table();
// Here I create my table with controls
int rows = 3;
int cols = 2;
for (int j = 0; j < rows; j++)
{
TableRow r = new TableRow();
for (int i = 0; i < cols; i++)
{
TableCell c = new TableCell();
LiteralControl l = new LiteralControl("row " + j.ToString() + ", cell " + i.ToString());
// save a reference to the control for editing
list.Add(l);
c.Controls.Add(l);
r.Cells.Add(c);
}
tbl.Rows.Add(r);
}
tableContainer.Controls.Clear(); // tableContainer is a Panel fixed in aspx page
tableContainer.Controls.Add(tbl);
}
protected void txt_TextChanged(object sender, EventArgs e)
{
// edit controls here
foreach (LiteralControl ctrl in list)
{
ctrl.Text = "TextChanged";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.