您的位置:首页 > 编程语言 > ASP

asp.net 导出excel时报类型“DataGridLinkButton”的控件“dgExcel__ctl1__ctl0”必须放在具有 runat=server 的窗体标记内 解决方法

2007-09-08 15:32 1071 查看
google_ad_client = "pub-2048279401139630";google_ad_slot = "8856771542";google_ad_width = 728;google_ad_height = 90;document.write("");
一般我们导出excel的方法函数如下:


public static void DataGridToExcel(DataGrid grdTemp,DataSet dsTemp,string strFileName)




...{


grdTemp.AllowPaging=false; //设置不能分页




grdTemp.DataSource=dsTemp; //重新绑定数据源


grdTemp.DataBind();




//常规导出方法




System.IO.StringWriter SW = new System.IO.StringWriter();


System.Web.UI.HtmlTextWriter HTW=new System.Web.UI.HtmlTextWriter(SW);


grdTemp.RenderControl(HTW);




//Page为要导出的对象,当前是Page,如果是DataGrid,DataList等都可以


System.Web.HttpContext.Current.Response.Buffer=true;


System.Web.HttpContext.Current.Response.Clear();


System.Web.HttpContext.Current.Response.ClearContent();


System.Web.HttpContext.Current.Response.ClearHeaders();


System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";


//Response.ContentType是输出流的 HTTP MIME 类型


//Response.ContentType --- word文件


//application/vnd.ms-excel --- excel文件


//...


System.Web.HttpContext.Current.Response.Charset="UTF-8";


System.Web.HttpContext.Current.Response.ContentEncoding=System.Text.Encoding.Default;


System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName + ".xls");


//attachment --- 作为附件下载


//inline --- 在线打开


//filename如过是中文,则可以用HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8)


//进行进行编码,以解决文件名乱码的问题


System.Web.HttpContext.Current.Response.Write(SW.ToString());


System.Web.HttpContext.Current.Response.Flush();


System.Web.HttpContext.Current.Response.Close();


}

不过当我们导出excel时报如下的错误信息:

类型“DataGridLinkButton”的控件“dgExcel__ctl1__ctl0”必须放在具有 runat=server 的窗体标记内。

说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

异常详细信息: System.Web.HttpException: 类型“DataGridLinkButton”的控件“dgExcel__ctl1__ctl0”必须放在具有 runat=server 的窗体标记内。

源错误:

[code]行 91: 			System.IO.StringWriter SW = new System.IO.StringWriter();
行 92: 			System.Web.UI.HtmlTextWriter HTW=new System.Web.UI.HtmlTextWriter(SW);
行 93: 			grdTemp.RenderControl(HTW);
行 94:
行 95: 			//Page为要导出的对象,当前是Page,如果是DataGrid,DataList等都可以

[/code]

<asp:BoundColumn DataField="REGTYPE" SortExpression="REGTYPE" HeaderText="注册类型"></asp:BoundColumn>

如果想正常导出Excel,那么有两种解决方法:
方法一:
去掉导出excel中的所有服务器端控件,把sortexpression属性也去掉。
方法二:
在后台代码加上下如下代码:




public override void VerifyRenderingInServerForm(Control control)




...{


//base.VerifyRenderingInServerForm (control);


}

这样就可以解决导出excel时报“DataGridLinkButton”的控件“dgExcel__ctl1__ctl0”必须放在具有 runat=server 的窗体标记内错误了。
其中问题有可能如下:
datagrid控件中,具有一些服务器端控件,如linkbutton等。linkbutton有可能是在datagrid表头加了排序表达式如:
google_ad_client = "pub-2048279401139630";google_ad_slot = "8856771542";google_ad_width = 728;google_ad_height = 90;document.write("");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐