Fearghal
Fearghal

Reputation: 11407

how to persist dynamic control properties

Scenario: I have added a asp textbox control dynamically to my page via the c# code behind. I have a button that removes that textbox, replaces it with a lbl of the text in the textbox.

Problem: When i push the button the page_init->page_load->page_prerender sequence kicks off, wiping my textbox control.

I init the textbox via a method in 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?

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?

Upvotes: 0

Views: 116

Answers (1)

mybirthname
mybirthname

Reputation: 18127

You don't show code. I will answer you with words.

You should always add the controls, this is happening on CreateChildControl Method

    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.

After that when you are going to 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. You can check it in view source of the page. After that no problems like yours should happen !

Upvotes: 1

Related Questions