Answered by:
DropDownList control has index of 0 - ViewState not maintaining value

Question
-
User-718146471 posted
Ok, maybe I am overlooking something stupid or maybe not enough coffee, but when I set the value of my SelectedIndex to a viewstate parameter, it holds on to it but then as soon as it has been set, the selected index drops back to 0. Any ideas how to fix this? Do I need to use a hidden field to hold the value? I thought viewstate would take care of this.Friday, July 22, 2016 2:46 PM
Answers
-
User2103319870 posted
Are you loosing the selectedindex after a postback, if so then on Pageload ensure that you are loading the dropdownlist inside the IsPostback block like given below.Otherwise the selection will get reset as dropdownlist will get reset on each postback. This will apply only if you load the dropdownlist on pageload
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //Load your dropdownlist here } }
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Saturday, July 23, 2016 3:56 PM
All replies
-
User475983607 posted
There is no need to explicitly set the SelectedIndex to a ViewState value as this happens automatically in Web Forms as long as ViewState is enabled.
If you are using ViewState in business logic to set the value of the SelectedIndex based on other processing then I would assume you have a bug somewhere.
Is there anyway you can post the code or an example so we can reproduce the issue?
Saturday, July 23, 2016 3:00 PM -
User2103319870 posted
Are you loosing the selectedindex after a postback, if so then on Pageload ensure that you are loading the dropdownlist inside the IsPostback block like given below.Otherwise the selection will get reset as dropdownlist will get reset on each postback. This will apply only if you load the dropdownlist on pageload
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //Load your dropdownlist here } }
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Saturday, July 23, 2016 3:56 PM -
User-718146471 posted
Yeah, that was it. I had the code right originally but that bit got lost; something odd happened in team foundation restoring an older version of the code when I checked it out.
Monday, July 25, 2016 10:28 AM