简体   繁体   English

保留asp.net中的动态控件

[英]Retain Dynamic Controls in asp.net

I have page on which I have 10 panel controls. 我有一个页面,我有10个面板控件。 Each of these Panels have approx 10 TextBoxes which I create dynamically using following code 这些面板中的每一个都有大约10个TextBoxes ,我使用以下代码动态创建

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);

I have some values retrieved from Database in those TextBoxes . 我在这些TextBoxes从数据库中检索了一些值。 I can change those values and I also have one Save button. 我可以更改这些值,我也有一个保存按钮。 On Click event of this button, I loop through TextBoxes of each panel to save modified data. 在此按钮的Click事件中,我遍历每个面板的TextBoxes以保存修改后的数据。

protected void btnSave_Click(object sender, EventArgs e)
{
    foreach (TextBox txt in Panel_0.Controls.OfType<TextBox>())
    {

    }
}

But, when I click on Save button, I can not find any TextBox Control in my for loop. 但是,当我单击“保存”按钮时,我在for循环中找不到任何TextBox控件。 Also on post back, these controls gets vanished from my page. 同样在回发后,这些控件从我的页面消失了。 How can I save the Controls and their Data so that I can retrieve it on Button Click event. 如何保存控件及其数据,以便我可以在Button Click事件中检索它。

Dynamic controls are lost after postback. 回发后动态控件丢失。 You have to re-created them after each post-back. 每次回发后都必须重新创建它们。 you will have to make use of View-State 你将不得不使用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++;
}

Please visit the following Urls: 请访问以下网址:

ASP.Net Dynamic Controls ViewState: Retain state for dynamically created controls on PostBack ASP.Net动态控件ViewState:保留PostBack上动态创建的控件的状态

Retaining State for Dynamically Created Controls in ASP.NET applications 保留ASP.NET应用程序中动态创建的控件的状态

ViewState in Dynamic Control 动态控制中的ViewState

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM