views:

936

answers:

2

I have a listview that adds controls in the ItemDataBound Event. When the postback occurs, I cannot find the new controls. After a bit of research, I found that ASP .NET needs these controls created every time, even after postback. From there I moved the function to bind the ListView outside of the if (!Page.IsPostBack) conditional. Now I get the dynamic controls values but the static controls I have are set to their defaults. Here is a sample of what I am trying to accomplish:

For brevity, I left some obvious things out of this example.

<asp:ListView runat="server" ID="MyList" OnItemDataBound="MyList_ItemDataBound">
    <LayoutTemplate>
        <asp:PlaceHolder runat="server" ID="itemPlaceholder" />
    </LayoutTemplate>

    <ItemTemplate>
        <asp:PlaceHolder runat="server" ID="ProductPlaceHolder">
            <asp:TextBox runat="server" ID="StaticField" Text="DefaultText" />
            <asp:PlaceHolder ID="DynamicItems" runat="server" />
        </asp:PlaceHolder>           
    </ItemTemplate>
</asp:ListView>

and here is the codebehind:

protected void MyList_ItemDataBound(object sender, System.Web.UI.WebControls.ListViewItemEventArgs e) {
    PlaceHolder DynamicItems = (PlaceHolder)e.Item.FindControl("DynamicItems");
    DynamicItems.Controls.Add(textbox);
}

So, like I said, if I only databind when Page != PostBack then I cant find my dynamic controls on postback. If I bind every time the page loads then my static fields get set to their default text.

A: 

Very similar question (instead of populating a ListView the guy is generating a set of buttons). Briefly, you'll find that you have to store the items in the list in your Viestate - than fish it out on Postback and re-populate the list.

Note that this solutions implies dropping data-binding (which you might not wanna do for others reasons).

Hope it helps.

JohnIdol
Yes, but the controls are created when the listview databinds. If I bind the listview after a postback, I may get my dynamic controls, but my static controls get set to their default values.
Russ Bradberry
I am suggesting to drop data-binding altogether - it is not clear from my answer, I'll edit in a minute. If you have the data source you can easily iterate and create the controls yourself.
JohnIdol
+2  A: 

Try moving the data binding of the ListView into the OnInit() event.

Phaedrus
wow, this worked perfectly. can you explain the reason behind this? i dont understand why just moving it to page_init fixed this.
Russ Bradberry