e mërkurë, 19 shtator 2007

Add rows to asp table web control dynamically

Came across this 'constraint' recently and was amazed to find not much solution exist in .net world for this.

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)Session["rowList"];
}
//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 :(

5 komente:

Anonymous tha...

Funcionou legal. Por enquanto essa foi a melhor solução que encontrei.
t+

borocin tha...

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:

rowList.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...

Alex tha...

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.

The page will keep track of the session state automatically.

梦中林 tha...

When the Wow Gold wolf finally found the Buy Wow Goldhole in the chimney he crawled wow gold cheap down and KERSPLASH right into that kettle of water and that was cheap wow gold the end of his troubles with the big bad wolf.
The next day the cheapest wow gold little pig invited his mother over . She said "You see it is just as mygamegoldI told you. The way to get along in the world is to do world of warcraft gold things as well as you can." Fortunately for that little pig, he buy cheap wow gold learned that lesson. And he just lived happily ever after! wow gold .

santhosh tha...

Perfectly useful for me , I appreciate the way it is described. Thanks so much..Santhosh