Dynamic Text Box Add on button click and data session in asp.net

825 Views Asked by At

QUESTION UPDATE

I am using this piece of code for cor adding multiple labels on button click. But each and every time it gives count value 0 and after execution only same label comes.

 int count = (int)ViewState["count"];
        for (int i = 0; i <= count; i++)
        {
            TextBox txtnew = new TextBox();
            txtnew.ID = "label_" + (i + 1);
            txtnew.Text = "label_" + (i + 1);
            ViewState["count"] = i;
            pnlControl.Controls.Add(txtnew);
        }
 ViewState["count"] = count + 1;

What i want now is how to keep that data of each control binded to it in its more convenient way.

2

There are 2 best solutions below

4
On BEST ANSWER

Dynamic controls are lost on every PostBack, so you need to keep track of the created ones somewhere and recreate them when the page is reloaded.

See my anwer here: How to dynamically create ASP.net controls within dynamically created ASP.net controls

It is about buttons but the basic principle is the same. Just replace Button with Label and it will work.

3
On

That's cause it's a web application and thus the session is not retained cause web applications are stateless in nature. So, every post back you get a new page instance which will have int count is 0. Solution: Use Session to store the data for future re-use like

int count = pnlControl.Controls.OfType<Label>().ToList().Count;
Session["count"] = count;

Retrieve it back on postback request

if(Session["count"] != null)
  count = (int)Session["count"];