Reputation: 42427
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.
Upvotes: 0
Views: 763
Reputation: 42427
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.
Upvotes: 0
Reputation: 42427
In the code-behind, doing the data-binding in the page's Init
event rather than Load
event works around the problem. However, a disadvantage of this is some control values are not populated during Init
.
Upvotes: 0
Reputation: 1307
Usually you can set the EnableViewState to "true" - as below:
<asp:DropDownList ... EnableViewState="true" ...>
</asp:DropDownList>`
But I am not 100% sure if it works the same way inside a DataList, but I am guessing it should.
You can learn more about the view state from Understanding ASP.NET View State.
Make sure you only enable the ViewState for the controls you absolutely need, otherwise you would run into memory issues. From the above source (emphasis mine):
The EnableViewState property is defined in the System.Web.UI.Control class, so all server controls have this property, including the Page class. You can therefore indicate that an entire page's view state need not be saved by setting the Page class's EnableViewState to False. (This can be done either in the code-behind class with Page.EnableViewState = false; or as a @Page-level directive - <%@Page EnableViewState="False" %>.
Upvotes: 1
Reputation: 2742
First check Page view state is set to True of False. Including EnableViewState="true" will definitely serve your purpose here, you need not to save the selection in session etc.
Upvotes: 0