Binding grid after generating pdf and creating download - c#

I have a page with grid that generates PDF files using iTextSharp dll. The code is as following:
var document = new Document();
bool download = true;
if (download == true)
{
PdfWriter.GetInstance(document, Response.OutputStream);
BindGrid();
}
string fileName = "PDF" + DateTime.Now.Ticks + ".pdf";
try
{
document.Open();
// adding contents to the pdf file....
}
catch (Exception ex)
{
lblMessage.Text = ex.ToString();
}
finally
{
document.Close();
BindGrid();
}
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.Flush();
Response.End();
BindGrid();
}
I need to bind the grid once the download window pops up, or after user clicks to download it doesn't matters, I just need the grid to bind after the user generates the pdf file. I have tried binding the grid on numerous places as you can see, but none of them worked, the grid binds only after I refresh the page :(.
Is there any way I can do this ???

Response.End ends the page life cycle.
I suggest you to:
Generate the PDF file and save it on the server
Bind the grid
Flush the generated file
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindGrid(); // Bind the grid here
// After reloading the page you flush the file
if (Session["FILE"] != null)
FlushFile();
}
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
// Generate & Save PDF here
Session["FILE"] = fullFilePath; // The full path of the file you saved.
Response.Redirect(Request.RawUrl); // This reload the page
}
private void FlushFile()
{
string fullFilePath = Session["FILE"].ToString();
Session["FILE"] = null;
// Flush file here
}
Hope this helps.
Cheers

Related

How to export excel from clicking chart legend?

I have created a few charts dynamically and would like to export the data to excel using closedxml.
I created a custom item on legend and when I click it, the page posts back and the event handler was raised properly. But I couldn't get the save window to pop up, hence not being able to save the excel file. Help me please?
I am using C# on asp.NET Framework 4.5.
Here's a simplified version of my code.
protected void Page_Load(object sender, EventArgs e)
{
Add_Chart();
}
public void Add_Chart()
{
System.Web.UI.DataVisualization.Charting.Chart Add_Chart1 = new System.Web.UI.DataVisualization.Charting.Chart();
//Create Chart here
//Add chart to htmltablecell
Add_Chart1.Click += Chart_Legend_Click;
}
protected void Chart_Button_Click(object sender, ImageMapEventArgs e)
{
string sheetname = "trial";
string filename = "trial.xlsx";
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add(sheetname);
HttpResponse httpResponse = Response;
httpResponse.Clear();
httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
httpResponse.AddHeader("content-disposition", "attachment;filename=" + filename);
//Create header and data rows here
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
workbook.SaveAs(memoryStream);
memoryStream.WriteTo(httpResponse.OutputStream);
memoryStream.Close();
}
httpResponse.End();
}

How to download PDF file from files on button click?

I want to dowlnload a PDF file on a button click. I've try like that:
protected void lbtnDownload_Click(object sender, EventArgs e)
{
if (lbtnDownload.Text != string.Empty)
{
else if (lbtnDownload.Text.EndsWith(".pdf"))
{
Response.ContentType = "application/pdf";
}
string filePath = lbtnDownload.Text;
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
Response.TransmitFile(HttpContext.Current.Server.MapPath("~/") + "\\PDF\\" + filePath );
Response.End();
}
}
But nothing happens, I mean when I debug it there is no exception, but the file is not downloading.
Does anyone knows where my mistake is, and what I should do to download the PDF?
Try this
protected void btnUpload_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(txtName.Text)) return;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + txtName.Text);
string filePath = Server.MapPath(Path.Combine("~/SavedFolder/PDF", txtName.Text));
Response.TransmitFile(filePath);
Response.End();
}

crystal report failed

I've created a crystal report with parameter,but it does not load the value. It simply shows the heading only, I mean column names only. Please check my code and correct me. And I was tried in that to load the report to pdf format, that shows an error like "load report failed". Please correct me.
protected void Button2_Click(object sender, EventArgs e)
{
ReportDocument reportdocument = new ReportDocument();
reportdocument.Load(Server.MapPath("CrystalReport.rpt"));
reportdocument.SetDatabaseLogon("", "", "Aravind", "MySampleDB");
reportdocument.SetParameterValue("MRNO", TextBox1.Text);
CrystalReportViewer1.ReportSource = reportdocument;
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
EXPORTREPORT();
}
private void EXPORTREPORT()
{
MemoryStream oStream;
Response.Clear();
Response.Buffer = true;
ReportDocument reportdocument = new ReportDocument();
reportdocument.Load(Server.MapPath("CrystalReort.rpt"));
reportdocument.SetDatabaseLogon("", "", "Aravind", "MySampleDB");
reportdocument.SetParameterValue("MRNO",TextBox1.Text);
CrystalReportViewer1.ReportSource = reportdocument;
oStream = (MemoryStream)reportdocument.ExportToStream(ExportFormatType.PortableDocFormat);
//oStream = (MemoryStream)crReport.ExportToStream(ExportFormatType.PortableDocFormat);
Response.ContentType = "application/pdf";
try
{
//write report to the Response stream
Response.BinaryWrite(oStream.ToArray());
Response.End();
}
catch (Exception ex)
{
Label2.Visible = true;
Label2.Text = "ERROR:" + Server.HtmlEncode(ex.Message.ToString());
}
finally
{
//clear stream
oStream.Flush();
oStream.Close();
oStream.Dispose();
}
Are you sure the name of your report is CrystalReort.rpt? Instead of a more common name CrystalReport.rpt.
Is it also located in the root of your website?
Cast value to required type , if its number then Convert.ToDouble(TextBox1.Text)
What type of MRNO is?
Also try below code, that might help you.
rptDoc.ExportOptions.ExportDestinationType = ExportDestinationType.NoDestination;
Stream getStreams = rptDoc.ExportToStream(ExportFormatType.PortableDocFormat);
byte[] getbytes = GetStreamAsByteArray(getStreams);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Length", getbytes.Length.ToString());
Response.BinaryWrite(getbytes);
Write the below code in the load event of the page.
if (crystalReportDoc != null)
{
crystalReportDoc.Close();
crystalReportDoc.Dispose();
GC.Collect();
}

Download from the tree node within a folder

protected void Page_Load(object sender, EventArgs e)
{
field1.Text = (string)(Session["rolename"]); //from the page before. eg:IT Folder
field2.Text = (string)(Session["fullname"]);
if (Page.IsPostBack == false)
{
System.IO.DirectoryInfo RootDir = new System.IO.DirectoryInfo("C:\\Documents and Settings\\itdept\\Desktop\\Files\\"+ field1.Text);
TreeNode RootNode = OutputDirectory(RootDir, null);
MyTree.Nodes.Add(RootNode);
}
}
protected void click(object sender, EventArgs e) //onselectednodechanged from the treenode in aspx page
{
string file = ("C:\\Documents and Settings\\itdept\\Desktop\\Files\\" + field1.Text + "\\" + MyTree.SelectedValue);
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment;filename=" + file);
Response.ContentType = "text/xml";
Response.WriteFile(file); // here is the problem
Response.End();
}
**i can download files from the IT Folder, but in case there is a folder inside the IT Folder and i want to download something from that folder, i cannot download it.
does anyone have an idea how to make all things inside a folder even in a folder is downloadable?
thank you. :D

Dynamically added link button click event does not execute

I have dynamically added few link buttons inside a grid view with this code:
protected void gvTicketStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string compositeFiles = e.Row.Cells[3].Text;
// split the string into individual files using delemeter "?"
string[] fileSet = compositeFiles.Split('?');
e.Row.Cells[3].Text = "";
foreach (string str in fileSet)
{
if (str != null)
{
// add a link button to the cell of the data grid.
LinkButton lb = new LinkButton();
lb.Text = "Download File";
lb.ID = str; // str is file URL
lb.Click += new EventHandler(lbStatus_click);
e.Row.Cells[3].Controls.Add(lb);
}
}
}
}
In my event handler, I have read the URL from the ID and downloading the file as octet stream.
private void lbStatus_click(object sender, EventArgs e)
{
string fileName = ((Control)sender).ID;
FileInfo file = new FileInfo(fileName);
if (fileName != string.Empty && file.Exists)
{
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=" + fileName.Substring(fileName.LastIndexOf("\\") + 1));
Response.AddHeader("content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
}
The link bottons appear in the webpage fine, but the problem is when I click on them, the page simply gets refreshed and nothing happens. The event handler code never gets executed.
Is this problem related to postback of the page? if yes then how can I solve it?
You need to suscribe to the command event of the grid view and add whatever information you need to the CommandArgs property.
EDIT: Added example
public void Page_Load(object sender, EventArgs e ){
gvTicketStatus.RowCommand += new EventHandler(RowCommand);
}
protected void gvTicketStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string compositeFiles = e.Row.Cells[3].Text;
// split the string into individual files using delemeter "?"
string[] fileSet = compositeFiles.Split('?');
e.Row.Cells[3].Text = "";
foreach (string str in fileSet)
{
if (str != null)
{
// add a link button to the cell of the data grid.
LinkButton lb = new LinkButton();
lb.Text = "Download File";
lb.CommandName = "download"; //this is useful if you need to add more links with different commands.
lb.CommandArgument = str;// str is file URL
e.Row.Cells[3].Controls.Add(lb);
}
}
}
}
In my event handler, I have read the URL from the ID and downloading the file as octet stream.
private void RowCommand(object sender, GridViewCommandEventArgs e)
{
string fileName = e.CommandArgument;
FileInfo file = new FileInfo(fileName);
if (fileName != string.Empty && file.Exists)
{
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=" + fileName.Substring(fileName.LastIndexOf("\\") + 1));
Response.AddHeader("content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
}
For more information, please read http://msdn.microsoft.com/library/system.web.ui.webcontrols.gridview.rowcommand(v=vs.80).aspx
I've seen this behavior many times before when adding controls dynamically. Make sure that the code which binds your datagrid (which in turn executes your gvTicketStatus_RowDataBound event) runs after each and every page postback. This needs to occur in order for the linkbutton control to persist its click event after the postback.

Categories

Resources