How to remove a Gridview from an ASPX page? - asp.net

I have an Aspx page that displays a GridView. The gridview would appear with data that was depending on which catergory was selected from a drop down menu. The user has the option to then download this as a CSV file (export to CSV). I now want the Gridview not to appear (beacuse it is so large it often just hangs) but instead to be able to download a CSV file with the data from the gridview. I have successfully built the button allowing for the download of this data by clicking the button. However, I now cannot open the page without the gridView appearing. I tried to comment out the Gridview code - this just broke the page. I tried to set the gridview as Visible="False" but this did not work either. What else can I do to prevent the gridview from appearing and the user to be taken straight to a download dialogue box?

wrap your Gridview to a div and set it to display:none in asp.net code –
Ex: <div id="divhidegrid" runat="server" style="display:none;" > <asp:GridView ID="gvtest" runat="server" > </div> like this

You can load your data in DataSet or DataTable from Code Behind and then export it directly to Excel/CSV without assigning it to GridView such as in the following example to export it to Excel:
Public Sub ExportToExcel(dt As DataTable)
If dt.Rows.Count > 0 Then
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim dgGrid As New DataGrid()
dgGrid.DataSource = dt
dgGrid.DataBind()
'Get the HTML for the control.
dgGrid.RenderControl(hw)
'Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Disposition", "attachment; filename=Data.xls")
Me.EnableViewState = False
Response.Write(tw.ToString())
Response.[End]()
End If
End Sub
If you get errors like control must be placed in inside of form tag you may also be required put the following code in your backend (Reference: export-data-to-excel-from-datatable-gridview-aspnet-csharp)
Public Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
C# Version of above code:
public void ExportToExcel(DataTable dt)
{
if (dt.Rows.Count > 0) {
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=Data.xls");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
public void VerifyRenderingInServerForm(Control control)
{
// Verifies that the control is rendered
}

Related

Gridview to Excel Issue

I have a chunk of code which extracts data from Grid View into excel file. But instead of extracting the grid view data it is copying entire data present in the html view into my excel as below:
How can I get only my Grid View data into excel?
My excel generation code is below. I don't use Response.End() as it throws ThreadAbortException.
protected void btnExcelGenerator_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridViewRefurb.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
Help is appreciated, thanks in advance
Do some changes
1) ASPX Page : Gridview within Panel
<asp:panel id = "panel_export" runat = "server" >
<asp:Gridview id = "Gridview" runat = "server">
</Gridview>
</asp:Panel>
2) ON Excel Export render panel instead of Gridview
panel_export.RenderControl(htmlWrite);

Datagrid from Contentplace holder aspx page, Form is on Master page

This is asp.net application in VB. I have a master page and it has several contenet place holders have child pages. I have datagrid on those child or sub pages. I am trying to export these ASP:datagrids to excel. I know we have good examples of doing this. I am using following method:
Dim excelFileName As String = "Filename" + "_" + Date.Today + ".xlsx"
Response.Clear()
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=" + excelFileName)
Dim stringWriter As New System.IO.StringWriter()
Dim textWriter As New HtmlTextWriter(stringWriter)
dgrid.RenderControl(textWriter)
Response.Write(stringWriter.ToString())
Response.End()
My problem is I am not able to do it because it says that for using this code the grid and button should be under tag with property runat=Server. My trials were.
Tried to add this grid to form using form.control.add(dGrid). It did not let me as I have <% %> code restriction. Which is requirement so I can not get rid of it.
Use Bind() method after datagrid is loaded, which ofcourse give me no values on excel.
Tried to use master page to findcontrol on run time from the loaded page. But still it says should be under tag with property runat=Server.
So Question Is : how to use the master page tag at the child (in Contentplaceholder)

Export pie chart to powerpoint using c#

i am trying to Export a pie chart to powerpoint slide uisng c# but not found any similar article which can help me...
please provide me some example or provide some useful link which can help me in achieving this functionality easily...
thanks,
Aman
we are using hipdf library but this is paid and we are converting html to image first and then showing this image on ppt slide. You can also do it by using inkscape exe file
In button_click event write following code.
GridView1.AllowPaging = false; //write this code only if paging is enabled.
GridView1.DataBind(); //write this code only if paging is enabled.
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.ppt");//for text file write FileName.txt
Response.Charset = "";
// If you want the option to open the Excel file without saving than comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ppt";\\for text file write vnd.txt
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
GridView1.AllowPaging = true; //write this code only if paging is enabled.
GridView1.DataBind();//write this code only if paging is enabled.
You will have to override function of VerifyRenderingInServerForm like this
public override void VerifyRenderingInServerForm(Control control)
{
//Keep it empty
}
And to avoid exception you have to set property of
<%# Page Language="C#" EnableEventValidation="false" %>

Gridvew.RenderControl returns empty string

I am trying to export a Gridview to excel. I bind the gridview to a collection and can see that it has 6 data rows but when i call the RenderControl it returns an empty string. Below is the code i am using
Gridview1.DataSource = data;
Gridview1.DataBind();
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
Gridview1.RenderControl(htw);
var outputHtml = sw.ToString();
when i check the outputHtml it is an empty string. What i am doing wrong in this piece of code.
One thing to note is that gridview is lying inside a form with runat='server' tag and i have not overridden the VerifyRenderingInServerForm method.
My best bet is that you have set the visibility of the GridView to false. This will prevent the control from rendering, because well...it's invisible now. The result is an empty string.
If you don't want to show the GridView, just set the Visibility to true before you execute your rendering code and set it back afterwards:
gv_sample.Visible = true;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
gv_sample.RenderControl(htw);
var outputHtml = sw.ToString();
gv_sample.Visible = false;
You possibly will run into trouble with the RenderControl method now. If so, make sure you have set EnableEventValidation="false" in the Page directive and override the VerifyRenderingInServerForm method:
public override void VerifyRenderingInServerForm(Control control)
{
return;
}

a ButtonField within DataGrid calling Vb.net as Javascript.... for streaming PDF?

I just noticed it last night,
Anyway, let's get to the interesting case here.
I have a ButtonField within DataGrid, and if you notice it here...
The Interface of that ButtonField is looks like a LINK.
But if we hover on it, it appeared as Javascript's call.
Here is the Image ScreenShot
Ya, that's the 1st case.
IT IS a javascript's call.
I didnt notice about it lately. (hehehe).
Then, if we click on that... it would call the createPDF() function. The function behind the scene (which I'm using VB.net) is to execute these code;
Protected Sub createPDF()
Dim document As New Document()
Dim mem As LengthFixingStream = New LengthFixingStream()
' instantiate a iTextSharp.text.pdf.Document
'Dim mem As New MemoryStream()
' PDF data will be written here
PdfWriter.GetInstance(document, mem)
' tie a PdfWriter instance to the stream
document.Open()
Dim titleFont = FontFactory.GetFont("Arial", 18, Font.BOLD)
document.Add(New Paragraph("Northwind Traders Receipt", titleFont))
document.Close()
' automatically closes the attached MemoryStream
Dim docData As Byte() = mem.GetBuffer()
' get the generated PDF as raw data
' write the document data to response stream and set appropriate headers:
Response.AppendHeader("Content-Disposition", "attachment; filename=testdoc.pdf")
Response.ContentType = "application/pdf"
Response.BinaryWrite(docData)
Response.[End]()
End Sub
But somehow... this of course would not deliver the PDF into the browser.
BEcause It's called by Javascript, nor the direct as Hyperlink (normally).
Thus, I'm wondering could we get the ASP.net Call new Window,
and then redirect the createPDF() result into it?
Correct me if i'm wrong...
Here is just some mockup so you get the idea. I haven't tested this. Basically you will have to put the above code in a new page...say "receipt.aspx" and execute it on the load event...you will need to setup an id parameter...if data is being pulled from the db to generate the pdf.
on the button click add the following
Dim sb As New System.Text.StringBuilder()
sb.Append("<script language='javascript'>")
sb.Append("window.open('receipt.aspx.htm?id=123'', 'Receipt',")
sb.Append("'width=800, height=800, menubar=yes, resizable=no');<")
sb.Append("/script>")
Dim t As Type = Me.GetType()
If Not ClientScript.IsStartUpScriptRegistered(t, "PopupScript") Then
ClientScript.RegisterStartUpScript(t, "PopupScript", sb.ToString())
End If
Notice the "id=123" querystring value I am passing to receipt.aspx?
You can then call that in the receipt.aspx page like this
Dim id as String = Request.QueryString("id")
CreatePDF(id)
...shoot! Just realized you are using a Grid...the principle remains the same, just wireup the buttons on RowDataBound event.
Protected Sub GridView_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim Id As String = DirectCast(e.Row.Cells(0).FindControl("quotationid"), Label).Text
Dim myButton As New Button
myButton = DirectCast(e.Row.Cells(4).FindControl("btnViewReceipt"), Button)
myButton.Attributes.Add("OnClick", "window.open('receipt.aspx?id=" + id + "','Receipt','scrollbars=yes','width=800,height=800')")
End If
End Sub

Resources