Wednesday, September 19, 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 :(

4 comments:

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

    ReplyDelete
  2. 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...

    ReplyDelete
  3. 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.

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

    ReplyDelete