2017-04-05 51 views
1

的form標籤中。'GridView'類型的控件'GridView1'必須放置在runat = server的form標籤內。'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]() 

回答

0

我想,你可以在下面的例子中使用。

.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 
+1

感謝您的幫助:) –

+0

ü歡迎:) –

相關問題