Everything is working fine, until the pdf file should be able to be clicked n viewd on the browser.Though the download link is working perfectly.
My grid...
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No files uploaded">
<Columns>
<asp:BoundField DataField="FileDate" HeaderText="Dated" />
<asp:BoundField DataField="FileName" HeaderText="File Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%# Eval("FilePath") %>' runat="server" OnClick = "DownloadFile" ></asp:LinkButton>
<asp:LinkButton ID="btnOpen" Text="View" Font-Bold="true" runat="server" onclick="btnpdf_Click" /></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My class
public class Thing
{
public string FilePath { get; set; }
public string FileName { get; set; }
public string FileDate { get; set; }
}
My PageLoad
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));
List<Thing> lst = new List<Thing>();
foreach (string filePath in filePaths)
{
lst.Add(new Thing()
{
//FileDate = File.GetCreationTime(filePath).ToShortDateString(),
FileDate = Path.GetFileName(filePath.Substring(0,35)),
FileName = Path.GetFileName(filePath.Substring(36)),
FilePath = filePath
});
}
GridView1.DataSource = lst;
GridView1.DataBind();
My download button
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath.Substring(36)));
Response.WriteFile(filePath);
Response.End();
My pdfview
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = "Application/pdf";
//Get the physical path to the file.
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath.Substring(36)));
//Write the file directly to the HTTP content output stream.
Response.WriteFile(filePath);
Response.End();
Still i cannot view the pdf on a browser...pls help
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text="Download" CommandArgument='<%#Eval("notice")%>' runat="server" onclick = "lnkDownload_Click" ></asp:LinkButton>
<asp:LinkButton ID="btnOpen" Text="View" CommandArgument='<%#Eval("notice")%>' Font-Bold="true" runat="server" onclick = "btnOpen_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
protected void lnkDownload_Click(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath.Substring(0)));
Response.WriteFile(filePath);
Response.End();
}
protected void btnOpen_Click(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = "Application/pdf";
//Get the physical path to the file.
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
// Write the file directly to the HTTP content output stream.
Response.Redirect(filePath);
Response.End();
}
For the pdfview - change the Content-Disposition to inline instead of attachment
Response.AppendHeader("Content-Disposition", "inline; filename=" + Path.GetFileName(filePath.Substring(36)));
Instead of opening PDF file in other browser, open that in a pop up.
In pop up add a iframe and give your PDF file path to it. No need to move to New window. You can preview in same window and when you give PDF file as a source to iframe it will by default give options to save and print.
Good luck.!
Related
I have a grid view showing product images:
<form id="form1" runat="server">
<asp:Button ID="btnDownload" runat="server" CssClass="dist-down-button" Text="Download Selected" OnClick="DownloadFiles" />
<asp:Button ID="Button1" runat="server" CssClass="dist-down-button" Text="Download All" OnClick="DownloadAll" />
<asp:GridView ID="GridView1" runat="server" CssClass="mydatagrid" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header" RowStyle-CssClass="rows" AllowPaging="True" OnPageIndexChanging="datagrid_PageIndexChanging" AutoGenerateColumns="false" EmptyDataText="No files available">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
<asp:Label ID="lblFilePath" runat="server" Text='<%# Eval("Value") %>' Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Text" HeaderText="Image Name" />
</Columns>
</asp:GridView>
</form>
Binding function: (matches all the files in the products folder with the product images list from database and show matching products)
protected void BindData()
{
images = GetProductImages();
string[] filePaths = Directory.GetFiles(Server.MapPath("~/upload/Products/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
if (images.IndexOf(Path.GetFileName(filePath)) > -1)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
}
}
GridView1.DataSource = files;
GridView1.DataBind();
}
protected void datagrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
Download All function: (look for the gridview list and download all the files listed)
protected void DownloadAll(object sender, EventArgs e)
{
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName(ProductUrl);
foreach (GridViewRow row in GridView1.Rows)
{
string filePath = (row.FindControl("lblFilePath") as Label).Text;
zip.AddFile(filePath, ProductUrl);
}
Response.Clear();
Response.BufferOutput = false;
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
Response.End();
}
}
When I click on Download All button it was downloading all the files correctly. BUT after I added the pagination the download all is now only downloading the current page.
Note: The checkbox is for selected download function. As you see I am not looking for checkboxes checked in the DownloadAll function.
Does anyone know why is this happening eventhough I am not looking for any checkbox in my function?
You could turn off paging and re-binding the GridView before exporting:
protected void DownloadAll(object sender, EventArgs e)
{
GridView1.AllowPaging = false;
BindData();
// ... your code
GridView1.AllowPaging = true;
BindData();
}
In Download All function, you have clearly writing that...take file path
only from gridview.. After the pagination...so it only take Current
Page Gridview data...not pickup all the data..
foreach (GridViewRow row in GridView1.Rows)
{
string filePath = (row.FindControl("lblFilePath") as Label).Text;
zip.AddFile(filePath, ProductUrl);
}
Solution:-
So, Whenever you binding the Gridview that time hold all data in
ViewState..
gridView.DataSource = dt;
gridView.DataBind();
ViewState["DownLoadGridData"]=dt as DataTable;
DataTable dt = ViewState["DownLoadGridData"] as DataTable;
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
if (row[FilePath] != null) // This will check the null values also (if you want to check).
{
// then add filepath
string filePath = row[FilePath].ToString();
zip.AddFile(filePath, ProductUrl);
}
}
}
Note:- you can develop your own logic also
I have developed a system to upload word file along with TITLE textbox but no idea how to display and download from gridview.
protected void UploadTender()
{
try
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/UploadedTenders/") + fileName);
HdnFieldUploadedTender.Value = fileName;
ResultLabel.ResultLabelAttributes("Tender Uploaded", ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
else
{
ResultLabel.ResultLabelAttributes("No file specified", ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
}
catch (Exception ex)
{
ResultLabel.ResultLabelAttributes(ex.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
finally { }
}
Gridview:
<asp:GridView runat="server" ID="grdviewUploadedTenders" OnRowCommand="grdviewUploadedTenders_RowCommand" DataKeyNames="pk_UploadedTenders_UploadedTenderID" AutoGenerateColumns="false" CssClass="table table-condensed table-bordered table-striped table-responsive">
<Columns>
<asp:BoundField DataField="pk_UploadedTenders_UploadedTenderID" HeaderText="Tender ID" />
<asp:BoundField DataField="UploadedTenderTitle" HeaderText="Tender Title" />
<asp:BoundField DataField="UploadedTenderRemarks" HeaderText="Remarks" />
<asp:BoundField DataField="UploadedTenderSystemEntryDateTime" HeaderText="Uploaded On" />
<asp:ButtonField CommandName="cmdEdit" ImageUrl="~/assets/global/images/shopping/edit.png" ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="25px" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~/assets/global/images/shopping/delete.png"
CommandName="cmdDelete" CommandArgument='<%# Container.DataItemIndex %>' OnClientClick="return confirm('Are you Sure ?');"
ControlStyle-Width="25px" ControlStyle-Height="20px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am storing file path in sql TABLE. It's been stored there but issue is getting and making it able to be downloaded.
Check this tutorial
Displaying the files from folder or directory in ASP.Net GridView
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
}
GridView1.DataSource = files;
GridView1.DataBind();
}
}
Downloading the Uploaded File from ASP.Net GridView
protected void DownloadFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
Response.WriteFile(filePath);
Response.End();
}
I wanted to display a list of files in a specific folder as hyperlinks, and when the user click on the link, it will open the respective file to prompt the user to download or view but there is a constant error saying:
{"Value cannot be null.\r\nParameter name: filename"} at the line context.Response.WriteFile(context.Request.QueryString["files"]);
I've tried lots of ways but to no avail.
ASHX file:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var directory = new DirectoryInfo("C:\\temp\\Safety&Security");
var files = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
//string[] files = Directory.GetFiles(#"C:\temp\Safety&Security");
//files = files.Substring(files.LastIndexOf(("\\")) + 1);
rpt.DataSource = files;
rpt.DataBind();
}
if (!Page.IsPostBack)
{
string[] files = Directory.GetFiles(#"C:\temp\marketing");
Repeater1.DataSource = files;
Repeater1.DataBind();
}
if (!Page.IsPostBack)
{
string[] files = Directory.GetFiles(#"C:\temp\IT");
Repeater2.DataSource = files;
Repeater2.DataBind();
}
}
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
string file = e.Item.DataItem as string;
HyperLink hyp = e.Item.FindControl("hyp") as HyperLink;
hyp.Text = file;
hyp.NavigateUrl = string.Format("~/Handlers/FileHandler.ashx?file={0}", file);
FileInfo f = new FileInfo(file);
FileStream s = f.Open(FileMode.OpenOrCreate, FileAccess.Read);
}
}
public void ProcessRequest(HttpContext context)
{
//Track your id
//string id = context.Request.QueryString["id"];
context.Response.Clear();
context.Response.Buffer = true;
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + context.Request.QueryString["files"]);
context.Response.WriteFile(context.Request.QueryString["files"]);
context.Response.End();
}
public bool IsReusable
{
get { return false; }
}
This is the index page codes:
<li class='has-sub'><a href='#'><span>Safety, QA & Security</span></a>
<ul>
<asp:Repeater ID="rpt" runat="server" OnItemDataBound="rpt_ItemDataBound">
<ItemTemplate>
<asp:HyperLink ID="hyp" runat="server" target="_blank" a href="/Handlers/FileHandler.ashx?id=7"/>
<%-- another method of listing all files in specific folder --%>
<%--<% foreach(var file in Directory.GetFiles("C:\\temp\\Safety&Security", "*.*", SearchOption.AllDirectories)) { %>
<li><%= file.Substring(file.LastIndexOf(("\\"))+1) %></li>
<% } %> --%>
</ItemTemplate>
</asp:Repeater>
</ul>
</li>
You've made a silly mistake!
hyp.NavigateUrl = string.Format("~/Handlers/FileHandler.ashx?file={0}", file);
context.Response.WriteFile(context.Request.QueryString["files"]);
You're setting the querystring as 'file' but reading the querystring as 'files' which doesn't exist. Try
context.Response.WriteFile(context.Request.QueryString["file"]);
EDIT:
Try this code. First add a file in your c:\temp called test.txt and put some text in there. In your aspx:
<li class='has-sub'><a href='/Handlers/FileHandler.ashx?file=c:\temp\test.txt'><span>Safety, QA & Security</span></a></li>
In your handler:
public void ProcessRequest(HttpContext context)
{
//Track your id
//string id = context.Request.QueryString["id"];
context.Response.Clear();
context.Response.Buffer = true;
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + context.Request.QueryString["file"]);
context.Response.WriteFile(context.Request.QueryString["file"]);
context.Response.End();
}
public bool IsReusable
{
get { return false; }
}
Set a breakpoint in your handler and make sure your handler gets hit when you debug. This code won't work as you need it to because of the other problem I mentioned in the comments about your data binding not working but you should at least get the querystring in your handler and the text file will download.
In the below code i get attachment file names in a session i have bind the documnetid,attachmentname and download.but when i select 1st attachmnet filename it is downloading second attchmt filename.My aim is to download what i select in grid view.
eg
document id attchfilename download
1 xxx view
2 yyy view
Markup
<asp:GridView ID="Attchdwnld" runat="server"
AllowPaging="true"
AllowSorting="true"
AlternatingRowStyle-CssClass="alt"
AutoGenerateColumns="false"
CellPadding="4"
CssClass="mGrid"
ForeColor="#333333"
PageSize="10"
PageSize-Mode="NumericPages"
PagerStyle-CssClass="pgr"
PagerStyle-Visible="true"
ShowFooter="false"
Width="100%"
OnRowCommand="Attchdwnld_RowCommand" >
<Columns>
<asp:TemplateField HeaderText="DocumentID" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="DocumentID" runat="server" Text='<%#Eval("DocumentID") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AttachmentFileName" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="AttachmentFileName" runat="server" Text='<%#Eval("AttachmentFileName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DownLoad" ItemStyle-Width="150px">
<ItemTemplate>
<asp:LinkButton ID="lnlbtnAttch" runat="server" Text="View" CommandName="Edit">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle Font-Bold="True" ForeColor="White" />
</asp:GridView>
Code-behind
protected void Attchdwnld_RowCommand(object sender, GridViewCommandEventArgs e)
{
var SearchDoc = (SearchDoc)Session["Documentname"];
lblMessage.Text = SearchDoc.AttachmentFileName;
string fileurl = "C:\\Search\\" + stName + "\\" + strtFolder + "\\" + lblMessage.Text;
string filename = fileurl;
if (filename != "")
{
string path = filename;
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
}
I don't see why you should store Session["Documentname"] in your code at all. So I am omitting that part.
Try this code
protected void Attchdwnld_RowCommand(object sender, GridViewCommandEventArgs e)
{
// gets the clicked row of your GridView
var row = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;
//gets the filename in the cliked row
var attachmentNameLabel = row.FindControl("AttachmentFileName") as Label;
//store it to lblMessage's Text
lblMessage.Text = attachmentNameLabel.Text;
var filePath = String.Format("C:\\Search\\{0}\\{1}\\{2}",
stName, strtFolder, lblMessage.Text);
var file = new System.IO.FileInfo(filePath);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
I have a gridview with a button for exporting it's data to an Excel file. When the button is clicked, I receive the following error:
Control 'gvLogNotice' of type 'GridView' must be placed inside a form tag with runat=server.
However, the Grid is within a form tag, I tried it both using a MasterPage and using a page w/o a MasterPage and still get the same error.
This is my Gridview snippet w/ button:
<form id="form1" runat="server">
<div style="width:600px;">
<asp:GridView ID="gvLogNotice"
runat="server"
AutoGenerateColumns="false"
ShowFooter="false"
OnRowCancelingEdit="gvLogNotice_RowCancelingEdit"
OnRowEditing="gvLogNotice_RowEditing"
OnRowUpdating="gvLogNotice_RowUpdating"
onpageindexchanging="gvLogNotice_PageIndexChanging"
OnRowDataBound="gvLogNotice_RowDataBound"
EmptyDataText="There are no data records to display."
DataKeyNames="LogNoticeID"
AllowPaging="true"
PageSize="10"
AllowSorting="true"
OnSorting="gvLogNotice_sorting"
Width="700px">
<Columns>
<asp:TemplateField HeaderText="Log No." Visible="false">
<ItemTemplate>
<%#Eval("LogNoticeID")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLogNoticeID" runat="server" Enabled="false" Text=' <%#Eval("LogNoticeID") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Date" SortExpression="DateLogged">
<ItemTemplate>
<%#Eval("DateLogged")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDateLogged" runat="server" Text=' <%#Eval("DateLogged") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Description" HeaderStyle-Width="50px" sortexpression="LogNoticeDescript">
<ItemTemplate>
<%#Eval("LogNoticeDescript")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLogNoticeDescript" runat="server" Text=' <%#Eval("LogNoticeDescript") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Responsible Party" sortexpression="ResponsibleParty">
<ItemTemplate>
<%#Eval("ResponsibleParty")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtResponsibleParty" runat="server" Text=' <%#Eval("ResponsibleParty") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Planned Date" SortExpression="PlannedDate" >
<ItemTemplate>
<%#Eval("PlannedDate")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPlannedDate" runat="server" Text=' <%#Eval("PlannedDate") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Case Number" SortExpression="CaseNumber">
<ItemTemplate>
<%#Eval("CaseNumber")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCaseNumber" runat="server" Text=' <%#Eval("CaseNumber") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Status" SortExpression="LogStatus">
<ItemTemplate>
<%#Eval("LogStatus")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLogStatus" runat="server" Text=' <%#Eval("LogStatus") %>'></asp:TextBox>
<asp:RangeValidator ID="rgvtxtLogStatus" runat="server" ControlToValidate="txtLogStatus" MaximumValue="1" MinimumValue="0" Text="Only a Value of 1 or 0 is allowed." />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="images/edit.png" Width="25"
Height="25" CommandName="Edit" />
<%-- <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/delete.png" CommandName="Delete"
OnClientClick="return confirm('Are you sure want to delete record?')" />--%>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div><asp:Button runat="server" ID="btnExport" Text="Export to Excel"
onclick="btnExport_Click" /></div>
</form>
...This is the code behind the button:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
gvLogNotice.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
...Second Approach: I also tried the following and I got an error that only one Form may exists:
protected void btnExport_Click(object sender, EventArgs e)
{
try
{
Response.ClearContent();
string attachment = "attachment; filename=MyExelFile.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter strWrite = new StringWriter();
HtmlTextWriter htmWrite = new HtmlTextWriter(strWrite);
HtmlForm htmfrm = new HtmlForm();
gvLogNotice.Parent.Controls.Add(htmfrm);
htmfrm.Attributes["runat"] = "server";
htmfrm.Controls.Add(gvLogNotice);
htmfrm.RenderControl(htmWrite);
Response.Write(strWrite.ToString());
Response.Flush();
Response.End();
}
catch (Exception ex) { }
}
Could I please get some help as to what I'm missing here? Thank you in Advance.
try this code on export button:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
GridViewBind();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
If you like to use 3rd party component then refer to this article.
http://www.codeproject.com/Articles/8411/C-class-library-for-exporting-data-to-CSV-Excel-fi
Try this
protected void Button2_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
private void ExportToExcel(DataTable dt)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Sheet1.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
GridView dgGrid = new GridView();
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in dgGrid.HeaderRow.Cells)
{
cell.BackColor = dgGrid.HeaderStyle.BackColor;
}
foreach (GridViewRow row in dgGrid.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = dgGrid.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = dgGrid.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
dgGrid.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();
}
}
This happens when you don't have the VerifyRenderingInServerForm in your code.
Simply put this snippet after your export code and it will go away.
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}