简体   繁体   English

如何保持动态控制属性

[英]how to persist dynamic control properties

Scenario: I have added a asp textbox control dynamically to my page via the c# code behind. 场景:我已经通过后面的C#代码向我的页面动态添加了一个asp文本框控件。 I have a button that removes that textbox, replaces it with a lbl of the text in the textbox. 我有一个按钮,用于删除该文本框,并将其替换为文本框中的文本的lbl。

Problem: When i push the button the page_init->page_load->page_prerender sequence kicks off, wiping my textbox control. 问题:当我按下按钮时,page_init-> page_load-> page_prerender序列开始,擦除了文本框控件。

I init the textbox via a method in page_prerender. 我通过page_prerender中的方法初始化文本框。

I could use viewstate to hold the value but see there is a enable view state etc. What is the standard way of persisting the dynamic controls textbox.text property across postbacks? 我可以使用viewstate来保存值,但是看到存在启用视图状态等。在回发之间持久保存动态控件textbox.text属性的标准方法是什么?

Code i have to date 代码我必须迄今为止

protected void Page_PreRender(object sender, EventArgs e)
{
    if (!IsPostBack)
    {

    }
    else
    {
         add_tb();
    }
}

private void add_tb()
{
    Textbox tb = new Textbox();
    pnlButtons.add(tb); //this is a panel init'd at design time which also includes a button
}
protected void imgBtn_Click_home(object sender, ImageClickEventArgs e)
{
    lblTest.Text=tb.Text; // where do i declare the tb to access it from here and to persist it?
}

Also, where do i declare the tb to access it from here and to persist it? 另外,我在哪里声明tb可以从此处访问它并保留它?

You don't show code. 您不显示代码。 I will answer you with words. 我会用语言回答你。

You should always add the controls, this is happening on CreateChildControl Method 您应该始终添加控件,这是在CreateChildControl方法上发生的

    TextBox txt;

    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        txt = new TextBox();
        txt.ID = "textBoxTest";
        txt.Visible = false;

        pnlButtons.add(txt); // till now pnlButtons should be created because you call first for base.CreateChildControls
    }

If you want to make the control not "added" in some case you just make him visible false by default. 如果要在某些情况下不“添加”控件,则默认情况下只需将其显示为false。

After that when you are going to OnPreRender 之后,当您要转到OnPreRender时

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        if(condition)//condition is when you show your checkbox
        {
            txt.Visible = true;
            lblTest.Visible = false;
        }
        else
        {
            lblTest.Visible = true;
            txt.Visible = false;
        }
    }

Make the control visible in right case. 在正确的情况下使控件可见。 When the control is visible false he is not added to the page. 当控件显示为false时,不会将其添加到页面中。 You can check it in view source of the page. 您可以在页面的视图源中对其进行检查。 After that no problems like yours should happen ! 之后,就不会发生像您这样的问题!

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

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