Link to home
Start Free TrialLog in
Avatar of kw66722
kw66722

asked on

Changing gridview to excel using button

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

Avatar of eugenbv
eugenbv
Flag of Romania image

Maybe is exactly what it says. Do you have <form runat="server" > ?
Avatar of kw66722
kw66722

ASKER

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.
 
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>
Avatar of kw66722

ASKER

<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)
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.

Avatar of kw66722

ASKER

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.
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.
Avatar of kw66722

ASKER

I will compare both and get back to you. And try your suggestions
Avatar of kw66722

ASKER

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

Are you doing this in a MasterPage?
Avatar of kw66722

ASKER

yes. Does that make a difference?
ASKER CERTIFIED SOLUTION
Avatar of eugenbv
eugenbv
Flag of Romania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kw66722

ASKER

I will try it creating a separate apsx just for the excel button.