Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top