2

我們試圖從GridView獲取HTML並將其存儲到字符串中,以便可以將字符串用作電子郵件的正文。將ASP.Net GridView HTML轉換爲字符串

到目前爲止,我們已經在使用該編碼的代碼隱藏:

Protected Sub EmailStudentList() 

    ' Get the rendered HTML. 
    '----------------------- 
    Dim SB As New StringBuilder() 
    Dim SW As New StringWriter(SB) 
    Dim htmlTW As New HtmlTextWriter(SW) 

    GridViewSummary.RenderControl(htmlTW) 

    ' Get the HTML into a string. 
    ' This will be used in the body of the email report. 
    '--------------------------------------------------- 
    Dim dataGridHTML As String = SB.ToString() 

    MsgBox(Server.HtmlEncode(dataGridHTML)) 
End Sub 

當運行顯示應用程序此錯誤:

Control 'BodyPlaceholder_GridViewSummary' of type 'GridView' must be placed 
inside a form tag with runat=server. 

所以我放在一個表單標籤在這個位置在標記:

​​

現在我們得到這個錯誤:

A page can have only one server-side Form tag. 

標記中沒有任何其他表單標記。

這是爲GridView的標記:在你的頁面

<asp:GridView 
    ID="GridViewSummary" 
    runat="server" 
    AllowPaging="True" 
    AllowSorting="True" 
    AutoGenerateColumns="False"> 

    <Columns> 
     <asp:BoundField DataField="Surname" HeaderText="Last Name" SortExpression="Surname" /> 
     <asp:BoundField DataField="Forename" HeaderText="First Name" SortExpression="Forename" /> 
     <asp:BoundField DataField="ParentName" HeaderText="Parents" SortExpression="ParentName" /> 
    </Columns> 

</asp:GridView>  
+0

您是否正在使用母版頁? – mcalex

+0

是的,我們正在那樣做。 –

+0

您可能會在母版頁中找到您缺少的表單控件。也許它缺少'runat =「server」'屬性 – mcalex

回答

5

添加下面的子,然後再試一次:

Public Overrides Sub VerifyRenderingInServerForm(control As Control) 
    Return 
End Sub 

編輯:

要關閉事件驗證,只需添加EnableEventValidation =「False」到你的aspx頁面的指令中。例如

<%@ Page EnableEventValidation="False" %> 
+0

感謝Vano的編碼。添加完後,現在顯示此錯誤:只能在Render()期間調用RegisterForEventValidation;我怎麼做? –

+0

看到我編輯的答案。 –

+0

感謝Vano。我把它放進去,它完美地工作。 :-) –