简体   繁体   中英

How Do I Get a Dynamic Control's Value after Postback?

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.

尝试将ListView的数据绑定移到OnInit()事件中。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM