Handling Post Back Events

In ASP.NET, each page is reloaded when a button is pressed or if you set the AutoPostBack property of a control to be True when its value has changed.  Since the same overridden methods are called and the same event notifications are sent during a post back, you need to make sure that you check the post back property of a page when writing your custom code.  For example, if you want to initialize a field to a value when the page is first displayed then you can handle an event and initialize this value.  But if you do not check the post back property in the event handler, your field will be initialized again when the page is being reposted and thus overwrite any user entered value.  This is perhaps the most common mistake made by .NET programmers.

C#:

if (!this.Page.IsPostBack)

{

     //  This code executes when the page is first loaded.

}

else

{

     //  This code executes during a button click or other postback.

}

//  This code executes in all cases.

Visual Basic .NET:

If Not (Me.Page.IsPostBack) Then

     ' This code executes when the page is first loaded.

Else

     ' This code executes during a button click or other postback.

End If

' This code executes in all cases.