?
Solved

Changing gridview to excel using button

Posted on 2011-05-10
13
Medium Priority
?
1,098 Views
Last Modified: 2012-05-11
I have a button that I am clicking to export a gridview to excel. I am getting the following error

Control 'lNamesGrid' of type 'GridView' must be placed inside a form tag with runat=server.
I tried adding

Public Overrides Sub VerifyRenderingInServerForm(control As Control)
      Return
End Sub

I get: Compiler Error Message: BC30284: sub 'VerifyRenderingInServerForm' cannot be declared 'Overrides' because it does not override a sub in a base class.

Protected Sub submitExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitExcel.Click
        If NamesGrid.HasControls = True Then
            '// Disable paging
            NamesGrid.AllowPaging = False
            NamesGrid.DataBind()
            '// exluded columns arraylist
            Dim defaultExcludedColumns As New ArrayList()

            '// Always exclude these columns
            defaultExcludedColumns.Add("") '// Removes columns without headers from the output.

            '// Send to base Excel export method 
            ExportGridView(NamesGrid, "ExcelFileName", defaultExcludedColumns)

            '// Rebind with paging enabled
            NamesGrid.AllowPaging = True
            NamesGrid.DataBind()
        End If

    End Sub

   
    ' This will export the gridview...
    '/// <summary>
    '/// Export GridView data to Excel.
    '/// </summary>
    '/// <param name="grdView">GridView control to export.</param>
    '/// <param name="filename">Filename of excel spreadsheet.</param>
    '/// <param name="excludedColumnList">ArrayList of columns to exlude.</param>
    Sub ExportGridView(ByVal grdView As GridView, ByVal filename As String, ByVal excludedColumnList As ArrayList)

        '// Clear response content & headers
        Response.Clear()
        Response.ClearContent()
        Response.ClearHeaders()

        '// Add header
        Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls")
        Response.Charset = String.Empty
        Response.Cache.SetCacheability(System.Web.HttpCacheability.Public)
        Response.ContentType = "application/vnd.xls"
        '// Start Excel Write
        '// Create stringWriter
        Dim stringWrite As New System.IO.StringWriter()

        '// Create HtmlTextWriter
        Dim htmlWrite As New HtmlTextWriter(stringWrite)

        '// Remove controls from Column Headers
        If (grdView.HeaderRow IsNot Nothing And grdView.HeaderRow.Cells IsNot Nothing) Then
            Dim ct As Integer
            For ct = 0 To grdView.HeaderRow.Cells.Count - 1 Step ct + 1
                ' Save initial text if found
                Dim headerText As String = grdView.HeaderRow.Cells(ct).Text

                ' Check for controls in header
                If grdView.HeaderRow.Cells(ct).HasControls() Then
                    ' Check for link button
                    If grdView.HeaderRow.Cells(ct).Controls(0).GetType().ToString() = "System.Web.UI.WebControls.DataControlLinkButton" Then
                        ' link button found, get text
                        headerText = (CType(grdView.HeaderRow.Cells(ct).Controls(0), LinkButton)).Text
                    End If

                    ' Remove controls from header
                    grdView.HeaderRow.Cells(ct).Controls.Clear()
                End If

                ' Reassign header text
                grdView.HeaderRow.Cells(ct).Text = headerText
            Next

        End If
        '// Remove footer
        If (grdView.FooterRow IsNot DBNull.Value) Then

            grdView.FooterRow.Visible = False
        End If

        '// Remove unwanted columns (header text listed in removeColumnList arraylist)
        Dim field As DataControlField
        For Each field In grdView.Columns

            If (excludedColumnList.Contains(field.HeaderText)) Then

                field.Visible = False
            End If
        Next

        '// Call gridview's renderControl
        grdView.RenderControl(htmlWrite)

        '// Write Response to browser
        Response.Write(stringWrite.ToString())

        Response.End()
    End Sub

Open in new window

0
Comment
Question by:kw66722
  • 7
  • 6
13 Comments
 
LVL 3

Expert Comment

by:eugenbv
ID: 35729276
Maybe is exactly what it says. Do you have <form runat="server" > ?
0
 
LVL 1

Author Comment

by:kw66722
ID: 35729407
Gridview

<asp:GridView ID="NamesGrid" runat="server" AutoGenerateColumns="False"
                DataSourceID="lNames" ShowHeader="False">

ERROR
Control 'lNamesGrid' of type 'GridView' must be placed inside a form tag with runat=server.
 
0
 
LVL 3

Expert Comment

by:eugenbv
ID: 35729459
I was not referring to the attribute of the GridView.
I mean: Do you have a <Form> tag that has attribute runat="server" ?
Something like

<form id="myForm" runat="server">

<asp:GridView ID="NamesGrid" runat="server" AutoGenerateColumns="False"
                DataSourceID="lNames" ShowHeader="False">

</form>
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 1

Author Comment

by:kw66722
ID: 35729661
<form id="Form1" runat="server">

The form is run at server.  I am getting the screen to display. I get the error when I click on the button to show it in excel format.  

When in debug mode the error is on the following line:

 grdView.RenderControl(htmlWrite)
0
 
LVL 3

Expert Comment

by:eugenbv
ID: 35729843
Add this to the vb code behind
    Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        Return
    End Sub

Open in new window


Solves a VS bug.

0
 
LVL 1

Author Comment

by:kw66722
ID: 35730155
I had tried that prior to asking for help.  When I do that I get the following error:

Error Message: BC30284: sub 'VerifyRenderingInServerForm' cannot be declared 'Overrides' because it does not override a sub in a base class.
0
 
LVL 3

Expert Comment

by:eugenbv
ID: 35732096
this is the test I made (listing of vb code)
Partial Public Class _Default
    Inherits System.Web.UI.Page

    Public lNames As List(Of String)

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        lNames = New List(Of String)
        lNames.Add("test")
        lNames.Add("test1")
        lNames.Add("test2")
        lNames.Add("test3")
        lNames.Add("test4")
        lNames.Add("test5")

        NamesGrid.DataSource = lNames
        NamesGrid.DataBind()
    End Sub

    Protected Sub submitExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitExcel.Click
        If NamesGrid.HasControls = True Then
            '// Disable paging
            NamesGrid.AllowPaging = False
            NamesGrid.DataBind()
            '// exluded columns arraylist
            Dim defaultExcludedColumns As New ArrayList()

            '// Always exclude these columns
            defaultExcludedColumns.Add("") '// Removes columns without headers from the output.

            '// Send to base Excel export method 
            ExportGridView(NamesGrid, "ExcelFileName", defaultExcludedColumns)

            '// Rebind with paging enabled
            NamesGrid.AllowPaging = True
            NamesGrid.DataBind()
        End If

    End Sub


    ' This will export the gridview...
    '/// <summary>
    '/// Export GridView data to Excel.
    '/// </summary>
    '/// <param name="grdView">GridView control to export.</param>
    '/// <param name="filename">Filename of excel spreadsheet.</param>
    '/// <param name="excludedColumnList">ArrayList of columns to exlude.</param>
    Sub ExportGridView(ByVal grdView As GridView, ByVal filename As String, ByVal excludedColumnList As ArrayList)

        '// Clear response content & headers
        Response.Clear()
        Response.ClearContent()
        Response.ClearHeaders()

        '// Add header
        Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls")
        Response.Charset = String.Empty
        Response.Cache.SetCacheability(System.Web.HttpCacheability.Public)
        Response.ContentType = "application/vnd.xls"
        '// Start Excel Write
        '// Create stringWriter
        Dim stringWrite As New System.IO.StringWriter()

        '// Create HtmlTextWriter
        Dim htmlWrite As New HtmlTextWriter(stringWrite)

        '// Remove controls from Column Headers
        If (grdView.HeaderRow IsNot Nothing And grdView.HeaderRow.Cells IsNot Nothing) Then
            Dim ct As Integer
            For ct = 0 To grdView.HeaderRow.Cells.Count - 1 Step ct + 1
                ' Save initial text if found
                Dim headerText As String = grdView.HeaderRow.Cells(ct).Text

                ' Check for controls in header
                If grdView.HeaderRow.Cells(ct).HasControls() Then
                    ' Check for link button
                    If grdView.HeaderRow.Cells(ct).Controls(0).GetType().ToString() = "System.Web.UI.WebControls.DataControlLinkButton" Then
                        ' link button found, get text
                        headerText = (CType(grdView.HeaderRow.Cells(ct).Controls(0), LinkButton)).Text
                    End If

                    ' Remove controls from header
                    grdView.HeaderRow.Cells(ct).Controls.Clear()
                End If

                ' Reassign header text
                grdView.HeaderRow.Cells(ct).Text = headerText
            Next

        End If
        '// Remove footer
        If (grdView.FooterRow IsNot DBNull.Value) Then

            grdView.FooterRow.Visible = False
        End If

        '// Remove unwanted columns (header text listed in removeColumnList arraylist)
        Dim field As DataControlField
        For Each field In grdView.Columns

            If (excludedColumnList.Contains(field.HeaderText)) Then

                field.Visible = False
            End If
        Next

        '// Call gridview's renderControl
        grdView.RenderControl(htmlWrite)

        '// Write Response to browser
        Response.Write(stringWrite.ToString())

        Response.End()
    End Sub

    Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        Return
    End Sub
End Class

Open in new window



and the aspx
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="test1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="NamesGrid" runat="server" AutoGenerateColumns="True" 
                ShowHeader="False">
        </asp:GridView>        
        <asp:Button ID="submitExcel" runat="server" Text="export" />
    </div>
    </form>
</body>
</html>

Open in new window


For me it works. Maybe you can spot a difference, besides the data from the datagrid :)
Hope it helps.
0
 
LVL 1

Author Comment

by:kw66722
ID: 35734419
I will compare both and get back to you. And try your suggestions
0
 
LVL 1

Author Comment

by:kw66722
ID: 35737423
this is the same problem. When I put the code I can a compile error


Error Message: BC30284: sub 'VerifyRenderingInServerForm' cannot be declared 'Overrides' because it does not override a sub in a base class.

Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        Return
    End Sub

Open in new window

0
 
LVL 3

Expert Comment

by:eugenbv
ID: 35737494
Are you doing this in a MasterPage?
0
 
LVL 1

Author Comment

by:kw66722
ID: 35743796
yes. Does that make a difference?
0
 
LVL 3

Accepted Solution

by:
eugenbv earned 2000 total points
ID: 35744217
It doesn't work in a MasterPage. There you have no VerifyRenderingInServerForm to override.
You should use the MasterPage for common controls (between pages) like menus or copyright. Move your other content to an .aspx content page.
0
 
LVL 1

Author Comment

by:kw66722
ID: 35746844
I will try it creating a separate apsx just for the excel button.
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Suggested Courses

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question