Wednesday, April 14, 2004

IsPostBack in WebParts
I just finished a research project for a client. The issue involved dynamically creating a DataViewWebPart object, tying it to some data (using XML files) and displaying it in a custom web part.

The client was able to build the web part just fine. When he tried to use some of the functionality of the DataView, like Sorting or Filtering, the DataView would not behave correctly. It would simply refresh itself in its original state.

I started looking at this, in my case I decided to use a DataGrid control to test it. With the ASP.NET DataGrid control, it's pretty easy to bind some data to it, and then to implement column sorting using the SortCommand event of the DataGrid.

I built my web part, implemented the SortCommand event and tested and got the same behavior. When I clicked a column to sort, it simply refreshed itself as it was originally.

Since I was creating the DataGrid and doing the binding in the CreateChildControls event of the web part, this event was firing over and over, essentially rebinding the control to the original data each time.

I figured I could then check for IsPostBack to avoid this databinding once the page had already been requested once. This didn't work either. I found in this MSDN article a discussion about how IsPostBack doesn't work in a WebPart, even though web parts are simply web user controls.

So, in the Load event of the DataGrid, I did a simple test to see if the grid already had data in it, and if not, then did the databinding. This way, the grid is being reloaded with ViewState instead of my databinding.

Private Sub _dg_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles _dg.Load
    If sender.Items.Count = 0 Then
        sender.DataSource = CreateDataSource() 'CreateDataSource creates & returns a DataView object
    End If
End Sub

This fixes the issue, which causes me to want to drink a beer. :)

No comments: