Click here to Skip to main content
13,351,731 members (45,165 online)
Rate this:
 
Please Sign up or sign in to vote.
See more:
--i have two button
1)search
2)ExportToExcel

on search i will get the data in gridview

on ExportToExcel the data will be in Excel

Search is working fine,

ExportToExcel Code is as follows
protected void ExportToExcel_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.AppendHeader("content-disposition","attachment;filename=Importeduserschedule.xls");
        Response.ContentType="application/excel";

        StringWriter stringwriter = new StringWriter();
        HtmlTextWriter htmltextwriter =new HtmlTextWriter(stringwriter);

        gvImported_Users.RenderControl(htmltextwriter);
        Response.Write(stringwriter.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {        
    }

Everything seems fine,But i am getting error as like this
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '<div>
	<table class=".</xml>"></table></div>


---just now i tried to include it in try catch block
protected void ExportToExcel_Click(object sender, EventArgs e)
    {
        try
        {
            Response.ClearContent();
            Response.AppendHeader("content-disposition", "attachment;filename=Importeduserschedule.xls");
            Response.ContentType = "application/excel";

            StringWriter stringwriter = new StringWriter();
            HtmlTextWriter htmltextwriter = new HtmlTextWriter(stringwriter);

            gvImported_Users.RenderControl(htmltextwriter);
            Response.Write(stringwriter.ToString());
            Response.End();
        }
        catch(Exception ex)
        {
            LogError.WriteError(ex);        
        }
    }

Its going in catch block.Its saying me like

unable to evaluate expression as the code is optimized or native frame is on top of the call stack


-------------------thanks for your commnet its almost 90 % completed----------------last help require----
--in my page load i have added the scriptmanager part

protected void Page_Load(object sender, EventArgs e)
{
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.btnexportToExcel);
try
{

//intRoleId = Convert.ToInt32(Session[TMS.Common.CommonConstants.CONST_ROLE_ID]);
strMainPage = Request.QueryString["IS_MAINPAGE"];
if (!IsPostBack)
{
txt_From_date.Text = (DateTime.Today.Date).ToShortDateString() + ' ' + (DateTime.Today.Date).AddHours(00).AddMinutes(00).ToShortTimeString();
txt_To_date.Text = (DateTime.Today.Date).ToShortDateString() + ' ' + (DateTime.Today.Date).AddHours(23).AddMinutes(59).ToShortTimeString();
intRoleId = Convert.ToInt32(Session[TMS.Common.CommonConstants.CONST_ROLE_ID]);
if (intRoleId == Convert.ToInt16(TMS.Common.CommonConstants.CONST_TRANSPORT_LOCAL_ROLEID))
{
ControlBinding.FillCombo(ddl_Hub, " HUB_MASTER", Session[TMS.Common.CommonConstants.CONST_COMPANY_ID].ToString(), Session[TMS.Common.CommonConstants.CONST_USER_HUB_ID].ToString(), Session[TMS.Common.CommonConstants.CONST_USER_ID].ToString(), "", "", "", false);
ddl_Hub.SelectedValue = Session[TMS.Common.CommonConstants.CONST_USER_HUB_ID].ToString();
ddl_Hub.Enabled = false;
}
else
{
ControlBinding.FillCombo(ddl_Hub, "ASSOCIATED_HUBS", Session[TMS.Common.CommonConstants.CONST_COMPANY_ID].ToString(), Session[TMS.Common.CommonConstants.CONST_USER_HUB_ID].ToString(), Session[TMS.Common.CommonConstants.CONST_USER_ID].ToString(), "", "", "", false);
}
}
// RoleBasedSecurity();

}
catch (Exception ex)
{
LogError.WriteError(ex);
}
}


----if i debug ,,,,it finally goes to HeaderHTML which is declared in my aspx page-----------------------------------------
</head>
<%HeaderHTML("Imported Users Schedule Details", 2, 0);
%>

---after it goes to HeaderHTML in my aspx page----it goes here-------------------------------


protected void HeaderHTML(string pageTitle, int folderLevel, int isPopup)
{
StringBuilder objStringBuilder = new StringBuilder();
try
{
switch (folderLevel)
{
case 0:
strFolderLevel = "";
break;
case 1:
strFolderLevel = "../";
break;
case 2:
strFolderLevel = "../../";
break;
case 3:
strFolderLevel = "../../../";
break;
case 4:
strFolderLevel = "../../../../";
break;
}
objStringBuilder.Append("<base target='_self'/><head><title>Transportal :: ");
objStringBuilder.Append(pageTitle);
objStringBuilder.Append("</title>");
objStringBuilder.Append("\n<META Http-Equiv='Cache-Control' Content='no-cache'>");
objStringBuilder.Append("\n<META Http-Equiv='Pragma' Content='no-cache'>");
objStringBuilder.Append("\n<META Http-Equiv='Expires' Content='0'>");
objStringBuilder.Append("\n<meta name='keywords' content='Transportal, Transport Management System, Employee Management System, Route Engine, Fleet Management, Routing, Web Employee Management System, Route planning'>");
objStringBuilder.Append("\n<meta name='description' content='Transportal is a Web Based fully automated Employee Transportation solution in integration with Infor Route Planning software'>");
objStringBuilder.Append("\n<meta name='author' content='HCL Technologies'>");
objStringBuilder.Append("\n<meta name='robots' content='all'>");
objStringBuilder.Append("\n<meta name='copyright' content=March 2009>");
objStringBuilder.Append("<link href='");
objStringBuilder.Append(strFolderLevel);
if (isPopup == 1)
{
objStringBuilder.Append("Utility/Style/TMS.css' type='text/css' rel='stylesheet'>");
}
else
{
objStringBuilder.Append("Utility/Style/TMS.css' type='text/css' rel='stylesheet'>");
}
objStringBuilder.Append("<script language='javascript' src='");
objStringBuilder.Append(strFolderLevel);
objStringBuilder.Append("Utility/JavaScript/commonFunctions.js'></script>");
objStringBuilder.Append("<script language='javascript' src='");
objStringBuilder.Append(strFolderLevel);
objStringBuilder.Append("Utility/JavaScript/CastleBusyBox.js'></script>");
//objStringBuilder.Append("\n<script language='javascript'>window.status='" + pageTitle + "'</script>");
//objStringBuilder.Append("\n<iframe id='BusyBoxIFrame' name='BusyBoxIFrame' frameBorder='0' scrolling='no' öndrop='return false;'></iframe>");
//objStringBuilder.Append("\n<SCRIPT>try{window.opener.document.getElementById('AlertDiv').style.display='hidden';}catch(e){} var busyBox = new BusyBox('BusyBoxIFrame', 'busyBox', 4, 'gears_ani_', '.gif', 125, 308, 172, 'BusyBox.htm') </SCRIPT>");
objStringBuilder.Append("\n</head>");
//writes the Header HTML
Response.Write(objStringBuilder.ToString());
SetScreenMessages();
}
catch (Exception e)
{
}
finally
{
objStringBuilder = null;
}
}

------------------------------------------------------------------------------------
I get the excelsheet pops up
But I get a popup after excel opens
--problems during pageload
missing file local settings\style.css
missing file ……………………………………………………..css
missing file .css
missing file ……………………………………………………..css
Finally excel opens
I get all the table in the entire page
And in below actual data exists[which I need]
But I don’t want entire details of the page,,,I only want the griddetails
Posted 2-Jul-13 19:55pm
Updated 10-Nov-17 9:33am
v6
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

  Permalink  
Comments
anurag19289 3-Jul-13 1:39am
   
hello-

brother i tried this

protected void ExportToExcel_Click(object sender, EventArgs e)
{
try
{

Response.ClearContent();
Response.AppendHeader("content-disposition", "attachment;filename=Importeduserschedule.xls");
Response.ContentType = "application/excel";


StringWriter stringwriter = new StringWriter();
HtmlTextWriter htmltextwriter = new HtmlTextWriter(stringwriter);

gvImported_Users.RenderControl(htmltextwriter);
Response.Write(stringwriter.ToString());
//Response.End();

HttpContext.Current.ApplicationInstance.CompleteRequest();
}

catch(Exception ex)
{

LogError.WriteError(ex);

}
}


--got error

Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '<div>
<table class'.
Rohan Leuva 3-Jul-13 1:48am
   
Do you have update panel in your page?
anurag19289 3-Jul-13 3:33am
   
yes update panel is there
Rohan Leuva 3-Jul-13 3:37am
   
Move button in update panel to outside the update panel.or Add a PostBackTrigger to your UpdatePanel that points at the button. This works great if the button is declared statically through markup on the page.
anurag19289 3-Jul-13 14:51pm
   
hello,,, that update panel is there in aspx page....and that is used for some other purpose,,,
and the button is outside the update panel
anurag19289 3-Jul-13 14:57pm
   
i have edited my question....kindly help me in this case
Rohan Leuva 4-Jul-13 0:18am
   
First of all remove all the code,unnecessary comments between the code and post only the following things:

1) Scriptmanager code block
2) updatepanel code block
3) export to excel function
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Error:
unable to evaluate expression as the code is optimized or native frame is on top of the call stack

It is because of Response.End() inside try catch block
Check : http://forums.asp.net/t/1488928.aspx[^]

Error:
Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.

It is because of Ajax request /update panel
Check :http://stackoverflow.com/questions/11221033/sys-webforms-pagerequestmanagerparsererrorexception-the-message-received-from-t[^]

http://stackoverflow.com/questions/1554728/the-message-received-from-the-server-could-not-be-parsed-common-causes-for-this[^]
  Permalink  
v2
Comments
anurag19289 3-Jul-13 2:57am
   
--this is almost completed but..

-- protected void Page_Load(object sender, EventArgs e)
{
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.btnexportToExcel);
try
{



//intRoleId = Convert.ToInt32(Session[TMS.Common.CommonConstants.CONST_ROLE_ID]);
strMainPage = Request.QueryString["IS_MAINPAGE"];
if (!IsPostBack)
{
txt_From_date.Text = (DateTime.Today.Date).ToShortDateString() + ' ' + (DateTime.Today.Date).AddHours(00).AddMinutes(00).ToShortTimeString();
txt_To_date.Text = (DateTime.Today.Date).ToShortDateString() + ' ' + (DateTime.Today.Date).AddHours(23).AddMinutes(59).ToShortTimeString();
intRoleId = Convert.ToInt32(Session[TMS.Common.CommonConstants.CONST_ROLE_ID]);
if (intRoleId == Convert.ToInt16(TMS.Common.CommonConstants.CONST_TRANSPORT_LOCAL_ROLEID))
{
ControlBinding.FillCombo(ddl_Hub, " HUB_MASTER", Session[TMS.Common.CommonConstants.CONST_COMPANY_ID].ToString(), Session[TMS.Common.CommonConstants.CONST_USER_HUB_ID].ToString(), Session[TMS.Common.CommonConstants.CONST_USER_ID].ToString(), "", "", "", false);
ddl_Hub.SelectedValue = Session[TMS.Common.CommonConstants.CONST_USER_HUB_ID].ToString();
ddl_Hub.Enabled = false;
}
else
{
ControlBinding.FillCombo(ddl_Hub, "ASSOCIATED_HUBS", Session[TMS.Common.CommonConstants.CONST_COMPANY_ID].ToString(), Session[TMS.Common.CommonConstants.CONST_USER_HUB_ID].ToString(), Session[TMS.Common.CommonConstants.CONST_USER_ID].ToString(), "", "", "", false);

}
}
// RoleBasedSecurity();

}
catch (Exception ex)
{
LogError.WriteError(ex);
}
}


</head>
<%HeaderHTML("Imported Users Schedule Details", 2, 0);
%>
protected void HeaderHTML(string pageTitle, int folderLevel, int isPopup)
{
StringBuilder objStringBuilder = new StringBuilder();
try
{
switch (folderLevel)
{
case 0:
strFolderLevel = "";
break;
case 1:
strFolderLevel = "../";
break;
case 2:
strFolderLevel = "../../";
break;
case 3:
strFolderLevel = "../../../";
break;
case 4:
strFolderLevel = "../../../../";
break;
}
objStringBuilder.Append("<base target='_self'/><head><title>Transportal :: ");
objStringBuilder.Append(pageTitle);
objStringBuilder.Append("</title>");
objStringBuilder.Append("\n<META Http-Equiv='Cache-Control' Content='no-cache'>");
objStringBuilder.Append("\n<META Http-Equiv='Pragma' Content='no-cache'>");
objStringBuilder.Append("\n<META Http-Equiv='Expires' Content='0'>");
objStringBuilder.Append("\n<meta name='keywords' content='Transportal, Transport Management System, Employee Management System, Route Engine, Fleet Management, Routing, Web Employee Management System, Route planning'>");
objStringBuilder.Append("\n<meta name='description' content='Transportal is a Web Based fully automated Employee Transportation solution in integration with Infor Route Planning software'>");
objStringBuilder.Append("\n<meta name='author' content='HCL Technologies'>");
objStringBuilder.Append("\n<meta name='robots' content='all'>");
anurag19289 3-Jul-13 2:59am
   
objStringBuilder.Append("\n<meta name='copyright' content=March 2009>");
objStringBuilder.Append("<link href='");
objStringBuilder.Append(strFolderLevel);
if (isPopup == 1)
{
objStringBuilder.Append("Utility/Style/TMS.css' type='text/css' rel='stylesheet'>");
}
else
{
objStringBuilder.Append("Utility/Style/TMS.css' type='text/css' rel='stylesheet'>");
}
objStringBuilder.Append("<script language='javascript' src='");
objStringBuilder.Append(strFolderLevel);
objStringBuilder.Append("Utility/JavaScript/commonFunctions.js'></script>");
objStringBuilder.Append("<script language='javascript' src='");
objStringBuilder.Append(strFolderLevel);
objStringBuilder.Append("Utility/JavaScript/CastleBusyBox.js'></script>");
//objStringBuilder.Append("\n<script language='javascript'>window.status='" + pageTitle + "'</script>");
//objStringBuilder.Append("\n<iframe id='BusyBoxIFrame' name='BusyBoxIFrame' frameBorder='0' scrolling='no' öndrop='return false;'></iframe>");
//objStringBuilder.Append("\n<SCRIPT>try{window.opener.document.getElementById('AlertDiv').style.display='hidden';}catch(e){} var busyBox = new BusyBox('BusyBoxIFrame', 'busyBox', 4, 'gears_ani_', '.gif', 125, 308, 172, 'BusyBox.htm') </SCRIPT>");
objStringBuilder.Append("\n</head>");
//writes the Header HTML
Response.Write(objStringBuilder.ToString());
SetScreenMessages();
}
catch (Exception e)
{
}
finally
{
objStringBuilder = null;
}
}
I get the excelsheet pops up

But I get a popup after excel opens

--problems during pageload
missing file local settings\style.css
missing file ……………………………………………………..css
missing file .css
missing file ……………………………………………………..css

Finally excel opens

I get all the table in the entire page

And in below actual data exists[which I need]

But I don’t want entire details of the page,,,I only want the griddetails
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

Following help for exporting data from Gridview to Excel.

HttpContext.Current.Response.Clear();
       HttpContext.Current.Response.ClearContent();
       HttpContext.Current.Response.ClearHeaders();
       HttpContext.Current.Response.Buffer = true;
       HttpContext.Current.Response.ContentType = "application/ms-excel";

       HttpContext.Current.Response.Write(@");
       HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=Reports.xls");
       HttpContext.Current.Response.Charset = "utf-8";
       HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");

       HttpContext.Current.Response.Write("<font style="font-size:10.0pt; font-family:Calibri;">");
       HttpContext.Current.Response.Write("<br><br><br>");
       //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
       HttpContext.Current.Response.Write("<table border="1" bgcolor="#ffffff" hold=" />          " bordercolor="#000000" cellspacing="0" cellpadding="0" style="font-size:10.0pt; font-family:Calibri; background:white;"> <tr>");
       //am getting my grid's column headers
       int columnscount = GridView.Columns.Count;

       for (int j = 0; j < columnscount - 1; j++)
       {      //write in new column
           HttpContext.Current.Response.Write("<td align="centre">");
           //Get column headers  and make it as bold in excel columns
           HttpContext.Current.Response.Write("");
           HttpContext.Current.Response.Write(GridView.Columns[j].HeaderText.ToString());
           HttpContext.Current.Response.Write("");
           HttpContext.Current.Response.Write("</td>");
       }
       HttpContext.Current.Response.Write("</tr>");
       foreach (DataRow row in table.Rows)
       {//write in new row
           HttpContext.Current.Response.Write("<tr>");
           for (int i = 0; i < table.Columns.Count; i++)
           {
               HttpContext.Current.Response.Write("<td align="left">");
               HttpContext.Current.Response.Write(row[i].ToString());
               HttpContext.Current.Response.Write("</td>");
           }

           HttpContext.Current.Response.Write("</tr>");
       }
       HttpContext.Current.Response.Write("</table>");
       HttpContext.Current.Response.Write("</br></br></br></font>");
       HttpContext.Current.Response.Flush();
       HttpContext.Current.Response.End();
  Permalink  
v2
Comments
anurag19289 3-Jul-13 14:53pm
   
i have some other problem....i have edited and improved the question ,,,,help me in this case,,,,
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 4

Make sure the button is registered for Ajax Postback.. The sample code snippet in Page Load solved my problem .. The issue was resolved by someone else in this page : c# - Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed - Stack Overflow[^]

protected void Page_Load(object sender, EventArgs e) {
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.btnExcelExport);
//Further code goes here....
}
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web03 | 2.8.180111.1 | Last Updated 10 Nov 2017
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100