crystal report failed - c#

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();
}

Related

Grid view is not being refreshed on exporting grid view to excel in asp.net

i am come up with scenario that while exporting grid view to excel its not refreshing my grid data source. Below is my code what i have done before. Below code is updating flag in database and then trying to refresh the grid data source in Fill Grid method.
protected void Process_Command(object sender, CommandEventArgs e)
{
if (!string.IsNullOrEmpty(Convert.ToString(e.CommandArgument)))
{
using (var transaction = context.Database.BeginTransaction())
{
DocumentOGP objDocumentOGP = context.DocumentOGPs.Find(Convert.ToInt64(e.CommandArgument));
objDocumentOGP.UpdationDate = DateTime.Now;
objDocumentOGP.DispatchStatusID = 2;
context.DocumentOGPs.Add(objDocumentOGP);
context.Entry(objDocumentOGP).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
transaction.Commit();
FillGrid();
}
ExportToExcel(Convert.ToInt64(e.CommandArgument));
}
}
Below is the Export to excel method.
public void ExportToExcel(Int64 OGPCode)
{
DataTable dtPickList =GeneralQuery.GetDocumentPickList(OGPCode);
if (dtPickList != null && dtPickList.Rows.Count>0)
{
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dtPickList;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Inbox.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
GridView1.DataSource = null;
Response.Write(Request.RawUrl.ToString());
}
}
public override void VerifyRenderingInServerForm(Control control)
{
}
Please help me what i am doing wrong. Thanks
Finally i found the way to refresh the grid view while exporting the grid view to excel. I just create new web form and put ExportGridToExcel() method in Page_Load and on button click it refresh the grid view data source and open new tab to download excel file. Below is my code.
protected void Process_Command(object sender, CommandEventArgs e)
{
if (Session["Status"] != "Refreshed")
{
if (!string.IsNullOrEmpty(Convert.ToString(e.CommandArgument)))
{
using (var transaction = context.Database.BeginTransaction())
{
DocumentOGP objDocumentOGP = context.DocumentOGPs.Find(Convert.ToInt64(e.CommandArgument));
objDocumentOGP.UpdationDate = DateTime.Now;
objDocumentOGP.DispatchStatusID = 2;
context.DocumentOGPs.Add(objDocumentOGP);
context.Entry(objDocumentOGP).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
transaction.Commit();
FillGrid();
Session["OGPCode"] = Convert.ToString(e.CommandArgument);
}
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "OpenWindow", "window.open('http://localhost:56430/DownLoadExcel','_newtab');", true);
}
}
}
Below is my Download excel file web-form and its implementation
public partial class DownLoadExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrEmpty(Convert.ToString(Session["OGPCode"])))
{
ExportToExcel(Convert.ToInt64(Session["OGPCode"]));
Session["OGPCode"] = null;
}
}
}
public void ExportToExcel(Int64 OGPCode)
{
DataTable dt = GeneralQuery.GetDocumentPickList(OGPCode);
//create a new byte array
byte[] bin;
string FileName = "Pick-List-" + DateTime.Now.ToString();
//create a new excel document
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create a new worksheet
ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add(FileName);
//add the contents of the datatable to the excel file
ws.Cells["A1"].LoadFromDataTable(dt, true);
//auto fix the columns
ws.Cells[ws.Dimension.Address].AutoFitColumns();
//loop all the columns
for (int col = 1; col <= ws.Dimension.End.Column; col++)
{
//make all columns just a bit wider, it would sometimes not fit
ws.Column(col).Width = ws.Column(col).Width + 1;
var cell = ws.Cells[1, col];
//make the text bold
cell.Style.Font.Bold = true;
//make the background of the cell gray
var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#BFBFBF"));
//make the header text upper case
cell.Value = ((string)cell.Value).ToUpper();
}
//convert the excel package to a byte array
bin = excelPackage.GetAsByteArray();
}
//clear the buffer stream
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
//set the correct contenttype
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//set the correct length of the data being send
Response.AddHeader("content-length", bin.Length.ToString());
//set the filename for the excel package
Response.AddHeader("content-disposition", "attachment; filename=\"" + FileName + ".xlsx\"");
//send the byte array to the browser
Response.OutputStream.Write(bin, 0, bin.Length);
//cleanup
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
When you update GridView or any control values dynamically you should render and export it to other application.
Sample: check with RenderControl method of GridView.
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "xyz.xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
}

How to open a pdf file in a WebForm application by search?

When I click on the listbox which search a PDF file, it's not opening.
The code is below. Any thoughts?
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string search = TextBox1.Text;
if (TextBox1.Text != "")
{
string[] pdffiles = Directory.GetFiles(#"\\192.168.5.10\fbar\REPORT\CLOTHO\H2\REPORT\", "*" + TextBox1.Text + "*.pdf", SearchOption.AllDirectories);
foreach (string file in pdffiles)
{
// ListBox1.Items.Add(file);
ListBox1.Items.Add(Path.GetFileName(file));
}
}
else
{
Response.Write("<script>alert('For this Wafer ID Report is Not Generated');</script>");
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string pdffiles = ListBox1.SelectedItem.ToString();
string.Format("attachment; filename={0}", fileName));
ProcessStartInfo infoOpenPdf = new ProcessStartInfo();
infoOpenPdf.FileName = pdffiles;
infoOpenPdf.Verb = "OPEN";
// Process.Start(file);
infoOpenPdf.CreateNoWindow = true;
infoOpenPdf.WindowStyle = ProcessWindowStyle.Normal;
Process openPdf = new Process();
openPdf.StartInfo = infoOpenPdf;
openPdf.Start();
}
First, you must save the file's full name to get it later. So, you must change from:
ListBox1.Items.Add(Path.GetFileName(file));
To:
ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file));
Then, you should send the file from the server to the client, like this:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string fileName = ListBox1.SelectedValue;
byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);
System.Web.HttpContext context = System.Web.HttpContext.Current;
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.AppendHeader("content-length", fileBytes.Length.ToString());
context.Response.ContentType = "application/pdf";
context.Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
context.Response.BinaryWrite(fileBytes);
context.ApplicationInstance.CompleteRequest();
}
Note: don't forget to initialize your ListBox with the property AutoPostBack setted to true.

Binding grid after generating pdf and creating download

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

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();
}

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