2013-07-11 67 views
1

我有網格視圖在我的用戶控制和我得到以下錯誤:無法使網格視圖

RegisterForEventValidation can only be called during Render(); 

我使用gv.RenderControl(htw);

我的代碼如下:

private void ExportToExcel(string strFileName, GridView gv) 
    { 
     Response.ClearContent(); 
     Response.AddHeader("content-disposition", "attachment; filename=" + strFileName); 
     Response.ContentType = "application/excel"; 
     System.IO.StringWriter sw = new System.IO.StringWriter(); 
     HtmlTextWriter htw = new HtmlTextWriter(sw); 
     gv.RenderControl(htw); 
     Response.Write(sw.ToString()); 
     Response.End(); 
    } 

並避免服務器控件創建外部窗體控件異常我使用下面的代碼:

public override void VerifyRenderingInServerForm(Control control) 
{ 
    /* Verifies that the control is rendered */ 
} 

但我在一個usercontrol中使用所有這些代碼,在基類中沒有這種方法。 我應該怎麼做,即使我放在我的頁面上面我放置我的用戶控制,但仍然我得到以上錯誤

另請注意我使用的是我已經形式標記已經。

回答

1

在頁面指令設置EnableEventValidation爲false解決我的問題。

<%@ Page ............ EnableEventValidation="false" %> 
0

C#

StringWriter sw = new StringWriter(); 
HtmlTextWriter hw = new HtmlTextWriter(sw); 
Page pg = new Page(); 
HtmlForm hf = new HtmlForm(); 

hf.Attributes.Add("runat", "server"); 
hf.Controls.Add(gv); 

pg.EnableEventValidation = false; 
pg.Controls.Add(hf); 
pg.DesignerInitialize(); 
pg.RenderControl(hw); 

Current.Response.Clear(); 
Current.Response.AddHeader("content-disposition", "attachment;filename=FileName.xls"); 
Current.Response.Charset = string.Empty; 
Current.Response.ContentType = "application/vnd.xls"; 
Current.Response.Write(sw.ToString()); 
Current.Response.End(); 

VB.NET

Dim sw As New StringWriter 
Dim hw As New HtmlTextWriter(sw) 
Dim pg As New Page() 
Dim hf As New HtmlForm() 

hf.Attributes.Add("runat", "server") 
hf.Controls.Add(gv) 

pg.EnableEventValidation = False 
pg.Controls.Add(hf) 
pg.DesignerInitialize() 
pg.RenderControl(hw) 

Current.Response.Clear() 
Current.Response.AddHeader("content-disposition", "attachment;filename=FileName.xls") 
Current.Response.Charset = String.Empty 
Current.Response.ContentType = "application/vnd.xls" 
Current.Response.Write(sw.ToString()) 
Current.Response.End() 
+0

我需要關於C#的幫助,而不是vb.net @nikita –

+0

@ubaidashrafmasoody,編輯,抱歉。此外,還有一個好工具:http://www.developerfusion.com/tools/convert/vb-to-csharp/ –

+0

RegisterForEventValidation只能在Render()中調用;這個錯誤我現在越來越@nikita –