In this article I will explain with an example, how to resolve the following error in ASP.Net.
RegisterForEventValidation can only be called during Render();
 
 
Error
The following error occurs when you try to render a control to Response i.e. exporting GridView to Excel, Word, PDF or CSV formats.
The ASP.Net compiler issues the Exception, since it feels the Event is invalid.
Server Error in 'ASP.Net' Application.
RegisterForEventValidation can only be called during Render();
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
 
Exception Details: System.InvalidOperationException: RegisterForEventValidation can only be called during Render();
 
 
Solution
The solution to this problem is to notify ASP.Net, that not to validate the event by setting the EnableEventValidation flag to FALSE.
You can enable EnableEventValidation in the following ways.
1. Using Web.Config
Inside the system.web section of the Web.Config file set the enableEventValidation to FALSE in the pages node. This will apply to all the pages in your website.
<pages enableEventValidation="false"></pages>
 
2. Using Page Directive
You can also set it in the @Page Directive of the page by setting EnableEventValidation to FALSE. Disabling the EnableEventValidation setting in @Page Directive will disable it only for the specific Page.
<%@Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" %>