1
votes

I've have on my aspx page an asp.net table control, containing asp.net TableRow objects;

My purpose is to dynamically add columns to this table by clicking some image button. The table consists of several TableRow objects, each containing by default an ASP.NET TableCell with some label. I am trying to add the columns by clicking the image button, supposedly adding a new cell to the cell collection of the row. For example if I want to add a column containing a dropdown list for a specific row, I do:

DropDownList ddl = new DropDownList();
            TableCell tableCell= new TableCell();
            tableCell.Controls.Add(ddl);
            tableRow.Cells.Add(tableCell);

The problem is that I can never go beyond one added column, because whenever I click the asp.net "AddColumn" button I've created, before I get to its handler somewhere in the life cycle the TableRow object dies, along with its collection of cells. I've thought about saving copies of the row objects in session somehow, but I can't think of a correct point in time to do the saving.

And anyhow - isn't the asp.net supposed to keep everything in viewstate? Please help and provide solutions. I'm totally confused.

The ASPX btw looks something like this:

<asp:TableRow runat="server" ID="RequestorEmailRow">
                        <asp:TableCell runat="server" Text="...">
                        </asp:TableCell>
                    </asp:TableRow>
1
You have to recreate your already added TableCells on every postback at the latest in Page_Load. Save the number of created Cells in ViewState. To avoid viewstate and event-handling issues with your DropDownLists you have also to ensure that they get the same ID on every postback.Tim Schmelter

1 Answers

1
votes

The ASP.NET viewstate only stores the values of controls, not the presence of controls themselves. The viewstate is deserialized between Page_Init and Page_Load. If you dynamically add <asp: style objects to a web page, you have to recreate them in Page_Init, or ASP.NET will not process their viewstate.

A nicer approach would be to use a GridView control (in the "Data" section of the toolbox.) Unlike the asp:Table, the asp:GridView's viewstate includes any rows you might have added.