Last post Mar 24, 2011 05:09 AM by sirdneo
Mar 23, 2011 07:28 PM|lalasa|LINK
Question1: I have a user control which has a dropdownlist and some textboxes. I disabled the viewSate on the user control. I decided to the databind on the dropdownlist on every postback. To start, I had my databinding in the Page_Load. When I did that,
I was able to access the values entered in the textboxes but the dropdownlist selected index was always 0 no matter what the user selects. Why?
Question 2: When I had my ViewState enabled, no problems with the databinding code in the Page_Load. But when ViewState is disabled, dropdownlist selected Index is always 0 no matter what the user selects. Why?
Question 3: After playing with it for a few hours, I moved the databinding code for dropdownlist into Page_Init. When I did this, I am able to access the dropdownlist selected Index correctly and my problem solved. Why?
Though I solved the problem by playing around, I would like to understand what is going on. Gurus, please help.
Mar 23, 2011 07:54 PM|mbanavige|LINK
the users selected (posted) value is going to be applied to the dropdownlist by the framework prior to page_load. If you databind it on page_load, you will wipe out the users selection.
if you databind it in page_init, then you are binding before the framework tries to apply the users selected value - so you dont wipe that selected value out since the framework hasnt set it quite yet. shortly after page_init is finished, the framework
will then attempt to apply the selectedvlaue that was received as part of the post data.
Mar 23, 2011 08:03 PM|lalasa|LINK
In that case, should the databinding always be in Page_Init?
Mar 24, 2011 04:29 AM|Dave Sussman|LINK
No, because view state is restore after init, but before load. So binding in load everytime overwrites the value loaded from viewstate. Do a search for "asp.net page lifecycle" and you'll see a bunch of articles as well as some good diagrams that show the
order of events.
Mar 24, 2011 05:09 AM|sirdneo|LINK
1- Whenever you databind a dropdown its index will become zero.
2- Dropdown selectedIndex property is bound after Page_Init event, so if you databind your ddl in Page_init selectedIndex will be zero, however before Page_load its value will be loaded from viewstate and its value will be the value which you selected from
3- When your page get postback, If you Bind your dropdown again in Page_load (without !IsPostBack) then your index will always be set to 0.
For details you can read a good artcle on page life cycle. Here is one:-
Also look some best practices in this article:-