Umair A.
Umair A.

Reputation: 6863

ASP.NET Many Nested Controls

I have 2 Repeaters one inside another.

<div id="result">
    <asp:Repeater runat="server" id="results">
        <Itemtemplate>
            <asp:Button ID="Button1" runat="server" Text="Add Color"></asp:Button>
            <asp:Repeater runat="server">
                <Itemtemplate>
                    <tr class="gradeX odd">
                        <asp:Button ID="Button2" runat="server" Text="Add Size"></asp:Button>
                        <td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
                        <td><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
                    </tr>
                </Itemtemplate>
                </asp:Repeater>
        </Itemtemplate>
    </asp:Repeater>
</div>

And on PageLoad I am populating both with DataBinding to List and List. The Button1 and Button2 is responsible for adding rows to each Repeater when clicked. The code is adding the rows to both perfectly but I noticed when I click the Buttons the data from the textbox isn't posted to the server so I collect from code behind. Is there something wrong I am doing?

Upvotes: 0

Views: 724

Answers (2)

YetAnotherUser
YetAnotherUser

Reputation: 9346

Make sure you re-bind your data on page postback as well. Page control tree needs to be recreated before you can access the posted values.

If you re-create and add the control in page_load, it would allow you to access the post back value, but any view state changes may get lost/over written.

If you can, then recreating the control tree in page_init results in cleanest solution as it would allow the dynamic controls view state to restored properly.

Read this excellent article on Dynamic Web Controls, Postbacks, and View State

Adding Controls at the Right Time

We already know that when adding controls dynamically through the page's code portion the controls must be added on every postback. But when in the page lifecycle should the controls be added? At first guess, we might decide to put such code in the Page_Load event handler, causing the controls to be added during the Load stage of the page's lifecycle. This would work fine if we don't need to worry about saving the controls' view state across postbacks, but if we do need to persist the view state of the dynamically added controls the Load stage is not where we should be adding these controls.

See following for The ASP.NET Page Life Cycle

Upvotes: 1

Andomar
Andomar

Reputation: 238068

In order for the server to read in the posted data, all ASP server controls have to exist right after Page_Init. Controls that do not exist at that point are not "deserialized", aka given values that were sent by the browser. Controls you create in Page_Load only arrive after the deserialization party.

Does it work if you move the DataBind from Page_Load to Page_Init?

Upvotes: 0

Related Questions