Caching techniques for paged GridView

Implementing output cache for the GridView is straight forward if the GridView doesn't require to provide paging functionality.

And so , if you don't need paging in the GridView , you can set the output cache on the page level and the GridView will be cached like any other control on the page.

However,the mentioned solution will not work if you tried to enable paging in the GridView , because the user will not be able to navigate to the other pages because page output cache is enabled.

There is many suggestions to the mentioned problem:

The first suggestion is to use the ListView control and configure it's pager control to use the Query string for passing page index,for more information about this solution ,read my post [here].

The second suggestion is to avoid using output cache on the page level, and just set the cache on the data source level ( by setting data source Enable Caching property to true).This will of course cache the data and not the GridView html output.This is a good solution to avoid hitting the database every time the user open the page.read more on how to use caching with data source controls [here]

The Third suggestion  is to use a user control and cache it's output using output cache, this will also require to vary the output cache of the user control based on the GridView page index.So that you will have a separate cached version of the user control for each GridView page.

To implement this solution , set the output cache directive in the user control:

<%@ OutputCache Duration="90" VaryByControl="HiddenField1"  %>

This will enable output cache on the user control for 90 seconds and will create a separate cached  version of the user control for each hidden Field (HiddenField1) value.

You need then to set the HiddenField value based on the Selected page index , something like this :

 

Protected Sub GridView1_PageIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.PageIndexChanged
HiddenField1.Value
= GridView1.PageIndex
End Sub

For more information about output cache directive , see this link.

 

Anas Ghanem

1 Comment

Comments have been disabled for this content.