我正在尝试将Gridview转换为Word文档。
我一直收到错误:
GridView1.RenderControl(hw)
说明
Control 'MainContent_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
代码:
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connStr, cmdStr As String
connStr = "connectionstring works"
cmdStr = "SELECT * FROM test;"
Dim ds As New DataSet
Dim dt As New DataTable()
Try
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand(cmdStr, conn)
conn.Open()
cmd.ExecuteNonQuery()
Using da As New SqlDataAdapter(cmd)
da.Fill(ds)
dt = ds.Tables(0)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
conn.Close()
cmd.Dispose()
conn.Dispose()
End Using
End Using
Catch ex As Exception
TextBox1.Text = ex.Message
End Try
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.doc")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-word"
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
GridView1.AllowPaging = False
GridView1.DataBind()
GridView1.RenderControl(hw)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()
End Sub
答案 0 :(得分:0)
将gridview放在<form runat="server">...</form>
标记