How to Solve Error Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server

Introduction: In previous articles I explained the solution to the errors The files use a different language,which is not allowed since they need to be compiled together and The SelectCommand property has not been initialized before calling 'Fill' Gridview and Solution to FileUpload control is not working in UpdatePanel and The GridView 'GridView1' fired event PageIndexChanging which wasn't handled and “WebForms UnobtrusiveValidationMode requiresa ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping namedjquery(case-sensitive)”. 
 
 Description: In this article I am going to explain how to solve/sort-out the error/problem “Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server” that usually occur while exporting GridView data to MS Excel file or MS Word or PDF or CSV(Comma separated value) file.

Reason and Solution: This exception occurs when one tries to export a GridView control to Word, Excel, PDF, CSV or any other formats. The .net compiler thinks that the control is not added to the form and is rendered, hence it throws this error even if the GridView control is inside the form with runat = “server” tag.

In this case you have to tell the compiler that the control is rendered explicitly by overriding the VerifyRenderingInServerForm event

C#.Net Code

The easiest solution is to add the following overriding function in the code behind file(.aspx.cs) as:

    public override void VerifyRenderingInServerForm(Control control)
    {
        //It solves the error "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
    }

VB.Net Code

The easiest solution is to add the following overriding function in the code behind file(.aspx.vb) as:

Public Overrides Sub VerifyRenderingInServerForm(control As Control)
        'It solves the error "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
    End Sub

Now run the web site and enjoy exporting GridView Data to Word, Excel, PDF, CSV etc.

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..