2010-02-25 35 views
1

我有一個gridvidew(GV2)。我希望用戶能夠將此GridView的內容導出到Excel電子表格以供離線處理。將gridview內容導出爲ex​​cel電子表格

這裏是我的子程序:

Protected Sub ExcelButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ExcelButton.Click 
     Response.ContentType = "application/vnd.ms-excel" 
     Response.Charset = "" 
     Me.EnableViewState = False 
     Dim stringWriter As New System.IO.StringWriter() 
     Dim htmlWriter As New System.Web.UI.HtmlTextWriter(stringWriter) 
     GV2.RenderControl(htmlWriter) 
     Response.Write(stringWriter.ToString()) 
     Response.End() 
    End Sub 

在點擊ExcelButton我得到的錯誤消息:類型的GridView'的

控制「GV2」必須放在一個表單標籤內有RUNAT =服務器。

控制GV2其實裏面:

<form id="form1" runat="server"></form> 

回答

2

有一個 'story' 這背後的錯誤消息。我會直接找到其中一個解決方案。

一下添加到ASPX文件的代碼隱藏:

Public Overrides Sub VerifyRenderingInServerForm(control As Control) 

End Sub 

此處瞭解詳情:

How to export GridView to Word using ASP.NET 2.0 and VB
CodeSnip: Exporting GridView to Excel

+0

感謝您的幫助。我添加了上面的代碼,現在得到:RegisterForEventValidation只能在Render()中調用; – Phil 2010-02-25 10:56:25

+0

我通過關閉事件驗證來解決這個問題.....通過在@page指令中添加EnableEventValidation =「false」...這是否存在潛在的危險? – Phil 2010-02-25 11:07:42

+0

@Phil,我假設你只關閉該特定頁面的事件驗證,則需要確保該頁面的回發事件不會被劫持以執行非法或不需要的操作。 – 2010-02-25 11:52:09