2

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 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Makes no difference.
It made it work but i have lost the previous control.
Then you are probably not storing that one in the session/viewstate.
Yup thanks i have got my answer . thanks for help and please vote up.
1

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"];

3 Comments

okay let me try this. and please vote up for better response.
Yes @rahul it did but also replaced the previous label.
Thanks for the help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.