[英]Error in Exporting Gridview to Excel
是的,我发现很多与此有关的问题,但我似乎找不到像我一样的确切情况。 因此,请花一些时间在下面查看我的代码:
我在内容占位符中包含此脚本
<script language="javascript" type="text/javascript">
function GetMac2() {
var macAddress = "";
var ipAddress = "";
var computerName = "";
var wmi = GetObject("winmgmts:{impersonationLevel=impersonate}");
e = new Enumerator(wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True"));
for (; !e.atEnd(); e.moveNext()) {
var s = e.item();
macAddress = s.MACAddress;
}
document.getElementById("<% =txtMACAdd.ClientID %>").value = unescape(macAddress);
} </script>
和用于将Gridview导出到excel的代码
HtmlForm form = new HtmlForm();
Response.Clear();
Response.Buffer = true;
string fileName = "Prenda of " + YearDropDownList.SelectedValue + "/" + MonthDropDownList.SelectedValue;
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
PrendaGridView.AllowPaging = false;
PrendaGridView.DataSource = (DataSet)ViewState["view"];
PrendaGridView.DataBind();
form.Controls.Add(PrendaGridView);
this.Controls.Add(form);
form.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
问题是我收到错误
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
当我包括上面的JavaScript时,如果我将其删除。 它运作良好。 所以有没有关于如何包含我的JavaScript的解决方法?
我像这样在page_load
上调用我的Java脚本
if(!isPostback)
{
string jvscript = "<script language='javascript'>GetMac2();</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "invoke", jvscript);
}
希望你能帮我谢谢!
我可以想到一种解决方法:
HTML:
<input id="tempInp" runat="server" type="hidden"></input>
C#:
tempInp.value = txtMACAdd.ClientID;
使用Javascript:
document.getElementById(document.getElementById("tempInp").value).value = unescape(macAddress);
这不会干扰javascript,并且javascript中没有服务器标记,因此您可以执行此操作this.Controls.Add(form);
编辑:
由于您使用服务器标记来获取控件的客户端ID,因此我认为控件的客户端ID和服务器ID不相同。
还有另一种非标准但简单的解决方法。 只需从浏览器的页面最终源复制txtMACAdd
的客户端ID, txtMACAdd
将其粘贴到document.getElementById("<% =txtMACAdd.ClientID %>").value
。
因为当我们执行document.getElementById("tempInp").value
, tempInp
控件的ClientID可能会有所不同,因此它将无法找到该控件,并且再次出现相同的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.