我有一个页面,我有10个面板控件.这些面板中的每一个都有大约10个TextBox,我使用以下代码动态创建
TextBox txt = new TextBox();
txt.ID = "txt_" + Month + "_" + Stage;
txt.Text = Value;
if (v == 0)
Panel_0.Controls.Add(txt);
else if (v == 1)
Panel_1.Controls.Add(txt);
我在这些TextBox中从数据库中检索了一些值.我可以更改这些值,我也有一个保存按钮.在此按钮的Click事件中,我遍历每个面板的TextBoxes以保存修改后的数据.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (TextBox txt in Panel_0.Controls.OfType<TextBox>())
{
}
}
但是,当我单击“保存”按钮时,我在for循环中找不到任何TextBox控件.
同样在回发后,这些控件从我的页面消失了.
如何保存控件及其数据,以便我可以在Button Click事件中检索它.
最佳答案 回发后动态控件丢失.每次回发后都必须重新创建它们.你将不得不使用View-State
protected int NumberOfControls
{
get{return (int)ViewState["NumControls"];}
set{ViewState["NumControls"] = value;}
}
private void addSomeControl()
{
TextBox tx = new TextBox();
tx.ID = "ControlID_" + NumberOfControls.ToString();
Page.Controls.Add(tx);
this.NumberOfControls++;
}
请访问以下网址:
ASP.Net Dynamic Controls ViewState: Retain state for dynamically created controls on PostBack
Retaining State for Dynamically Created Controls in ASP.NET applications