开发者

Dropdown.SelectedIndex doesnt have the correct value in the Page_Load event, but has the correct value in the Render event

I have an aspnet dropdown list in a usercontrol. This usercontrol gets loaded into the webform. There is a submit button on this page too. On postback the selectedItem does NOT s开发者_开发技巧how the right value in the Page_load handler but does show the right value in the Pre-render and render handlers. I was under the impression that the viewstate is set before page_load.


You're probably re-data-binding your dropdown list between the pre_render and page_load. Just like the event says, pre_render lets you do stuff before any of the controls on your page have been rendered. So once your page is rendered (before page_load) it's data-binding your dropdown list and erasing your selected value.

The easiest way to get around this is to data-bind your dropdown list in code only when it needs to be bound, like when the page is first loaded and not on post back.

if (!IsPostBack)
{
    //Do all of your data binding here
    DataBind();
}


Here is the solution which is best recommended. It lies in understandng the Page Life Cycle correctly!! Postback Controls like Drop Down List restore their posted state (the selected item of a Drop Down List posted). It forgets its selected value because you are rebinding it in Page_Load event, which is after the Drop Down List has been loaded with posted value (because View State is loaded after Page_Init event and before Page_Load event). And in this rebinding in Page_Load event, the Drop Down List forgets its restored selected item. The best solution is to perform the Data Binding in the Page_Init event instead of Page_Load event.

Do something like the below...

Suppose Drop Down List name is lstStates.

protected void Page_Init(object sender, EventArgs e)
{
   lstStates.DataSource = QueryDatabase(); //Just an example.
   lstStates.DataTextField = "StateName";    
   lstStates.DataValueField = "StateCode"; 
   lstStates.DataBind();
}

ASP.NET loads control's View State after Page_Init event and before Page_Load event, so Drop Down List's selectedIndex will not be affected, and you will get desired results magically!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜