The Problem scenario is like this:
I have a button and a textbox on a asp.net page:
<asp:Panel ID="Panel1" runat="server"
<asp:TextBox ID="GroupName" runat="server" Width="352px” />
<asp:Button ID="CreateGroup" runat="server" Text="Create"
<asp:PlaceHolder ID="PlaceHolder1" runat="server" />
When I click the button a label should be added dynamically to the placeholder located in the page:
The code in click event handler is as:
protected void CreateGroup_Click(object sender, EventArgs e)
Label label = new Label();
label.Text = GroupName.Text;
label.ID = GroupName.Text;
Its working but the problem is only last label are added to placeholder not the previous ones like:
If I put “Computer” in texbox and click,then the label is added .fine.
But If I put again “science” and click,then the label with “science” is added but the previous label is not rendered.
Well..here are some workarounds:
You can use this:SEE THE EXPLANATION WHY ITS HAPPENING:
Or the best solution is
Avoid dynamically creating controls.Actually creating controls dynamically is not the problem but maintaining there state might be.
Instead of storing dynamically added controls in ViewState,
You can use a collection to store them and store it in ViewState[Updated] . But I would again say,Avoid such things as much as possible..
If you get any better workaround ,Please do point me to that.
In my opinion,The best Solution will be the solution which will add the controls just like they are added at design time.But design time is different than runtime..Which occurs after compilation.
Please read the second comments that follows this post(Some nice cons of static variables in ASP.Net pages).
I am pasting here as i really liked the "Disadvantages of static variables in ASP.NET"
"You can use a collection to store them and declare it as static" I need to caution against this. I have learned some hard lessons with this.
I have many developers use static variables in their ASP.NET pages and NOT realize thast every user shares that variable.
If I have static array of strings that a button click adds to, and I have 2 users click that button, there will be 1 array 2 items in that array. A page where this is the intended affect desireable is rare.. and probally badly designed :).
The implications of adding a Control as a static member would be much, much worse. (GC collection and a threading nightmare!)
Storing Meta data using a client-specific storage, like Viewstate may be the way to go.