Requirement: Add rows dynamically to an asp table, web control(or say dynamically you want to keep on adding controls on click / some event)
Issue: I was able to add row but previously added row 'vanishes' from UI
Reason: Viewstate of dynamically created control is lost on next post back
Solution:
Added a session to store state of table and to render/recreate the control on post back
code as below in page_load event
if (Session["rowList"] == null)
{
//No row list, Create it.
rowList = new List
}
else
{
rowList = (List
}
//Recreate the table. (Prevents loosing data already entered into textboxes.)
DisplayTable();
There is an addrow method called on click (/ any event you like )
You have to add our newly formed row to our row List as below.
rowList.Add(tableRow);
Then save our Row List on to the session
Session.Add("rowList", rowList);
Call the DisplayTable();
Finally recreating table as below in DisplayTable function
protected void DisplayTable()
{
//Run through the row list, and add each one to the Table's Row Collection.
foreach (TableRow tr in rowList)
Table1.Rows.Add(tr);
}
Any other suggestion / idea you have please post it here....coz i am still not convinced by this idea :(
Funcionou legal. Por enquanto essa foi a melhor solução que encontrei.
ReplyDeletet+
You really should post the whole code, not just glimpse of it. This wasn't any help at all partly because code and explanations like:
ReplyDeleterowList.Add(tableRow);
Then save our Row List on to the session
Session.Add("rowList", rowList);
Call the DisplayTable();
First of all the rowList is only locally created in the PageLoad-part as you explain in the first part. So how are you going to add anything to it from a e.g. OnButtonClick-event?
Anyways, I am sure this will be helpful with more of your code, and not just some notes...
A better way is to keep track of how many of the dynamic controls you have in a Session variable. And then override OnInit() and recreate the objects within.
ReplyDeleteThe page will keep track of the session state automatically.
Perfectly useful for me , I appreciate the way it is described. Thanks so much..Santhosh
ReplyDelete