Search code examples
asp.netdrop-down-menupostbackviewstatedatalist

How can I retain a the selection of a DropDownList inside a DataList across a postback?


I'm a beginner at ASP.NET, but I'm trying to fix a bug in an application written by someone else: a drop-down list's selection is not retained across a postback.

Here are what I believe are the relevant parts of the code:

<asp:DataList ... OnItemDataBound="PopulateDropDownList">
    ...
    <FooterTemplate>
        <asp:DropDownList ... AutoPostBack="true" OnSelectedIndexChanged="DoSomething"/> 
    </FooterTemplate>                               
</asp:DataList>

I believe I could store the current selection in the session, a static variable or somewhere else, but this seems more like a work-around then a solution.


Solution

  • A colleague pointed out that the Page_Load method was re-binding the DataList even if the current request was a post-back. The problem was resolved by changing this to only bind the data to the DataList if the request is not a post-back.

    This seems to be the root cause of the problem, so I think this is the best solution.