1

“GridView”类型的控件“GridView1”必须放置在带有 runat=server 的表单标记内。

当我将 Gridview 导出到 Excel 时,出现这样的错误。你能帮助我吗?

我的代码示例如下。

 Dim SqlQuery As String = "SELECT * FROM vBasketbollTournamet ORDER BY 1 ASC"

 Dim cmd1 As New SqlCommand(SqlQuery, conn)
 Dim adp1 As New SqlDataAdapter(cmd1)
 adp1.Fill(dt2)

 GridView1.DataSource = dt2
 GridView1.DataBind()


 Dim oStringWriter As New StringWriter()
 Dim oHtmlTextWriter As New HtmlTextWriter(oStringWriter)

 GridView1.GridLines = GridLines.Horizontal
 GridView1.HeaderStyle.Font.Bold = True
 GridView1.RenderControl(oHtmlTextWriter)

 Response.Write(oStringWriter.ToString())
 Response.[End]()
4

1 回答 1

2

我认为,您可以使用下面的示例。

.aspx 文件内容

<!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>
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <br />
    <asp:Button ID="btntoExcel" runat="server" Text="GridView to Excel" onclick="btntoExcel_Click" />
    </form>
</body>
</html>

.aspx.vb 文件内容

Imports System.Drawing
Imports System.Data.SqlClient
Imports System.Data
Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim adapter As New SqlDataAdapter()
        Dim ds As New DataSet()
        Dim i As Integer = 0
        Dim sql As String = Nothing
        Dim connetionString As String = "Data Source=.;Initial Catalog=pubs;User ID=sa;Password=*****"
        sql = "select * from stores"
        Dim connection As New SqlConnection(connetionString)
        connection.Open()
        Dim command As New SqlCommand(sql, connection)
        adapter.SelectCommand = command
        adapter.Fill(ds)
        adapter.Dispose()
        command.Dispose()
        connection.Close()
        GridView1.DataSource = ds.Tables(0)
        GridView1.DataBind()
    End Sub
    Protected Sub btntoExcel_Click(ByVal sender As Object, ByVal e As EventArgs)
        Response.ClearContent()
        Response.AddHeader("content-disposition", "attachment; filename=gvtoexcel.xls")
        Response.ContentType = "application/excel"
        Dim sw As New System.IO.StringWriter()
        Dim htw As New HtmlTextWriter(sw)
        GridView1.RenderControl(htw)
        Response.Write(sw.ToString())
        Response.[End]()
    End Sub
    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        'Tell the compiler that the control is rendered
        'explicitly by overriding the VerifyRenderingInServerForm event.
    End Sub
  End Class
于 2017-04-05T13:39:45.997 回答