Sep 21 2006

ASP.NET Page Life Cycle Strikes Again

Published by at 2:37 am under Uncategorized

I just got asked a question that comes up quite often when someone starts working with ASP.NET…

 The question was:

“I have an asp.net 2.0 page which all I’m trying to do is populate a label control with the selected text of a dropdownlist control, whenever a button control is clicked.  It always puts the name of the first item in the dropdownlist in the label control, no matter what item I have selected.  Any ideas?”

The Code was:

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load With Me.DropDownList1.Items .Clear() .Add("Item 1") .Add("Item 2") .Add("Item 3") .Add("Item 4") End With End Sub Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click Label1.Text = DropDownList1.SelectedItem.Text End Sub End Class

The issue is that the Page_Load event will fire each time the page gets rendered, this includes on the post back from the button click so the list will be cleared then repopulated and the first item will always be selected once the Button1_Click event fires.

There is a good MSDN article for this ASP.NET Page Life Cycle Overview that covers this and cool diagram by Leon Andrianarivony ASP.NET Page Lifecycle diagram.

To solve this issue all that you need to do is use the Page.IsPostBack property in the Page_Load event like:

    Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then With Me.DropDownList1.Items .Clear() .Add("Item 1") .Add("Item 2") .Add("Item 3") .Add("Item 4") End With End If End Sub

This assumes ViewState is on…

Technorati tags: , ,

No responses yet

Comments are closed.