ASP.Net Gridview to Excel

Gridviews are mostly used to give the user a good view of data in a list, like a list of orders or reservations. For advanced web-applications, these users like to export these grids of data to an Excel-file, which they can work, filter and select more easily from to use the data for calculations. This is easy to do by sending the content from the table as a ms-excel content-type in the Response of a postback:

You’ll do have to change the page directive of that certain page that is returning the data, so it won’t render the “RegisterEventValidation can only be called during Render()” exception. Add ‘EnableEventValidation=”false”‘:

This will all work without any problems most of the time. But when you allow the columns to be generated automatically or have put code blocks within the column-templates of the gridview, you’ll be presented with this nasty error: “The controls collection cannot be modified because the control contains code blocks <% … %>“.

There certainly is a way to fix this! But it involves creating a regular HTML table, and populating that table with the rows of the GridView. The GridView rows will first be checked for any other controls within them, to be sure no other code-blocks can interfere. Best is to create a function for this, so you can reuse this at any time:

The code to export our Gridview to Excel from codebehind will then become this:

Leave a Reply

Your email address will not be published. Required fields are marked *