views:

4271

answers:

3

To Clarify to all this problem absolutely does not stem from rebinding of the controls and the value does not remain the initial value after binding.

I have a DropDownList on an aspx page which is being used in multiple projects.

Along the life cycle of the page the SelectedValue is changed prior to the handling of the SelectedIndexChanged event.

In one project when the code reaches the event handler the SelectedValue is back to what was posted from the client, while in the other the new SelectedValue is present.

Viewstate is on in both cases, the control is not being rebound and follows the exact same flow from all that I can gather.

The control is not being initialized again, I checked this thoroughly and does not retain the initial value but rather the value set in the code.

I actually need the posted value at the point of the event handler like is happening in the first project but do not understand why it would be changing back to the posted value and how to replicate this behavior in the second project.

I will be happy to clarify further if any of this is unclear.

+2  A: 

Maybe some initialization is performed twice in the on_load event because you dont check the page is posted back using IsPostBack in a test ?

It exactly happens to one of my colleague ten minutes ago :-)

controlbreak
the control is not being bound again and the logic is not relevant to a postback
YonahW
A: 

I usually see this behavior when I've forgotten to check IsPostback somewhere. The page will load all of the original data before going to the SelectedIndexChanged event handler.

TGnat
+1  A: 

Many people wrongly believe that DropDownLists must have ViewState on to be able retain selected value. I almost never have EnableViewState set to true on DropDownLists because they work fine in a form with the posted values. (And setting it to true on a DataBinding control will cause a long viewstate)

The posted value (selected item in the dropdown) is loaded from the post-parameters after OnInit in the page so if you bind the data to the dropdown in OnInit it will work fine.

If you bind in OnLoad, the selected Value will be overridden.

Perhaps you are databinding in the wrong event so that the selected value gets overridden by a DataBind-call on the dropdown?

ullmark
I was under the impression that viewstate was not necessary however it is there for the moment.Although I am changing the SelectedValue I am not rebinding the control and the code is exactly the same in both projects one of which does not lose the value.
YonahW