Monday, May 21, 2007

ViewState and Postback

I see a lot of people having problem preserving the controls's state when they perform postback. Most of these due to the fact they that don't quite understand how the form is processed on postback as seen in the following questions:

http://www.vbdotnetforums.com/showthread.php?t=18985
http://www.vbdotnetforums.com/showthread.php?t=19534

Have a look at this code snippet:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not IsPostBack Then

....

End If

LoadComboBoxes()

End Sub

IsPostBack will yield a True value if the page was posted back. You can use this to see whether this is the page load or refresh versus a post back and take appropriate action.

Let's say in the method LoadComboBoxes() you query the data from SQL and load that into the combo boxes. If you don't check for postback using IsPostBack, one of two things will happen:

1. If data binding is used on the controls or the Clear() method is called, all the state information gets wiped out and the controls will not retain their values.

2. If the Clear() method is not called then the combo boxes might have duplicate items added everytime you do a post back.

The recommended way for doing this is to move LoadComboBoxes inside the If statement that way it gets called once and also preserves postback data.

No comments: