我从GridView导出到Excel文件,我收到上述错误。
protected void ExportExcelButton_Click(object sender, EventArgs e)
{
GridViewExportUtil.Export("Issues.csv", this.gvIssues);
}
哪个电话:
public class GridViewExportUtil
{
public static void Export(string fileName, GridView gv, HashSet<string> selectedRows)
{
public static void Export(string fileName, GridView gv)
{
Table excelTable = new Table();
excelTable.GridLines = GridLines.Both;
excelTable.Rows.Add(gv.HeaderRow);
foreach (GridViewRow gvRow in gv.Rows)
{
excelTable.Rows.Add(gvRow);
}
StringWriter wrt = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(wrt);
System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form); // here is where the error is found
form.Controls.Add(gv);
form.RenderControl(htw);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName + DateTime.Today + ".xls");
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.Write(wrt.ToString());
HttpContext.Current.Response.End();
}
}
这段代码:
System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form); // here is where the error is found
form.Controls.Add(gv);
form.RenderControl(htw);
投入试图解决错误:Control 'cbSelectAll_0' of type 'CheckBox' must be placed inside a form tag with runat=server.
以下也没有帮助:VerifyRenderingInServerForm(Control)
:找不到合适的方法来覆盖
答案 0 :(得分:0)
此代码假定它作为Page方法的一部分执行。有Controls
是有意义的,因为Page.Controls
指的是页面上的控件集合。
不确定您是如何在其他类的静态实用程序方法中正常工作的(根据注释,此方法是GridViewExportUtil
类的一部分),但无论如何,修复它只是传递实例父控件(可以是页面)作为附加输入:
public static void Export(string fileName, GridView gv, System.Web.UI.Control parentControl)
{
...
parentControl.Controls.Add(form);
...
}
在您调用它的页面上,确保传递页面对象:
GridViewExportUtil.Export("some file name", GridView1, this);