codezoo
codezoo

Reputation: 593

Dynamically added TableRows not in Rows collection on Postback

I've added TableRows via code-behind to a table. The rows render on the page, but on PostBack, the rows are no longer part of the collection. What is the trick to get these rows to persist so that I can use them on PostBack?

.ascx

<asp:Table id="OrderItemsTable" runat="server">

.ascx.cs

TableRow itemRow = new TableRow();

// Ticket Quantity
TableCell cell1 = new TableCell();
cell1.Attributes.Add("align", "center");
TextBox ticket1QuantityTextBox = new TextBox();
ticket1QuantityTextBox.Width = Unit.Pixel(30);
ticket1QuantityTextBox.MaxLength = 3;
ticket1QuantityTextBox.Attributes.Add("class", "OrderItemTicketQuantityTB");
ticket1QuantityTextBox.Text = item.Quantity.ToString();
cell1.Controls.Add(ticket1QuantityTextBox);
itemRow.Cells.Add(cell1);
...
OrderItemsTable.Rows.Add(itemRow);

Upvotes: 4

Views: 2807

Answers (2)

Guru Kara
Guru Kara

Reputation: 6462

Yes, you need to construct the control tree with your dynamic controls in Page_Int event so that ASP.NET can load the ViewState data later into Page Control tree (which you will need to access the values from TextBox)

On a side not you should use Dynamic control only when the type of control is dynamic. Else you can achive the same using Repeater and listview

Truely Understanding Dynamic Controls

And here is the alternative to using Dynamic controls

ASP.NET: Alternatives to Dynamic Controls - Part 1

Upvotes: 1

Crab Bucket
Crab Bucket

Reputation: 6277

You need to contruct dynamic controls on the Page_Init event. Are you perhaps doing this in Page_Load or elsewhere. If they are added later than Page_Init then they don't participate in ViewState which will cause problems.

Upvotes: 3

Related Questions