I have come across many situations where I have needed to load data into a control on my page after the page is rendered. While this task in itself is fairly easy, it seems that many people run into a problem when they need to interract with the data in that control during subsequent postbacks. The problem is usually caused because they load the data during some specific event such as a button click event, but they do not persist that data. When the next postback occurs that control calls its databind method, however it no longer has any data available to bind to.

Here the LoadData() method is loading a simple list of objects into a GridView. This could be loading data from a database, a file, or pretty much anywhere. This will load the GridView just fine and everything will render to the page as you would expect.

The problem comes when we cause another postback to happen on the page. If we click our Search button in the image above without making any code changes our result is not at all what we want.

So how do we go about fixing this? The easiest way I've found is to create a Session backed property to store the data in. Then in the page's PreLoad event we can check to see if that property is null or not. If the property is not null then we set it as the datasource for our control and rebind the control.

I am using a simple list of objects here but you can just as easily use a DataTable or some other collection type. Now we can modify our original button load code a little bit to make use of our new property. At the same time we should also add the PreLoad event to our page and make sure that we are rebinding our data on each postback. The PreLoad event is a good choice for this because at this point all of our controls and their ViewState have been loaded.