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.");
}
}
Related
I am trying to export Grid data to csv file in asp.net i exported successfully but Audio File name column data is not displaying in downloaded file (it is button in TemplateField tag i need to print button text in csv file ) ,anything i forget to add ? How to fix this issue ? Thank you
.aspx code
<asp:GridView ID="GridView1" Font-Size="Medium" CssClass="mGrid" runat="server"
HeaderStyle-CssClass="header-center" PageSize="15"
AutoGenerateColumns="false" AllowPaging="True" AllowSorting="True"
OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<%--<asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-ForeColor="White" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Eval("Id")%>' CommandArgument='<%#Eval("Id")%>' Visible="false">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Vendor Name" />
<asp:BoundField DataField="AudFileSize" HeaderText="AudFileSize" />
<asp:BoundField DataField="AudFileDuration" HeaderText="AudFileDuration" />
<%-- <asp:TemplateField HeaderText="Audio FileName">
<ItemTemplate>
<asp:Button ID="btnAudioFileName"
Text='<%#System.IO.Path.GetFileNameWithoutExtension(Eval("AudioFileName").ToString())%>'
runat="server" CommandArgument='<%#Eval("AudioFileName")%>'
class="btn btn-link" CommandName="AudioFileName" />
<%-- <sup><asp:Label ID ="lblrepetedCount" Text='<%#Eval("Reject")%>' runat="server"
CommandArgument='<%#Eval("Reject")%>' CommandName="Reject"></asp:Label></sup>--%>
<%-- </ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Audio FileName">
<ItemTemplate>
<asp:Button ID="btnAudioFileName"
Text='<%#System.IO.Path.GetFileNameWithoutExtension(Eval("AudioFileName").ToString())%>'
runat="server" CommandArgument='<%#Eval("AudioFileName")%>'
class="btn btn-link" CommandName="AudioFileName" />
<%-- <sup><asp:Label ID ="lblrepetedCount" Text='<%#Eval("Reject")%>' runat="server"
CommandArgument='<%#Eval("Reject")%>' CommandName="Reject"></asp:Label></sup>--%>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="FirstName" HeaderText="Physician Name" />--%>
<%--<asp:BoundField DataField="PhysicianID" HeaderText="PhysicianID" />--%>
<asp:BoundField DataField="MrnNo" HeaderText="MrnNo" NullDisplayText=" " />
<asp:BoundField DataField="PatientName" HeaderText="PatientName" NullDisplayText=" "/>
<asp:BoundField DataField="PhysicianName" HeaderText="PhysicianName" />
<asp:BoundField DataField="Reject" HeaderText="Reject" Visible="false" />
<%--<asp:BoundField DataField="BucketName" HeaderText="Bucket Name" Visible="false" />--%>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblBucketName" runat="server" Text='<%#Eval("BucketName")%>' CommandArgument='<%#Eval("BucketName")%>' Visible="false">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs code here
protected void btnExportToCSV_Click(object sender, EventArgs e)
{
ExportGridToCSV();
}
private void ExportGridToCSV()
{
//To Export all pages
GridView1.AllowPaging = false;
FillData();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Transcribeworkdetails.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridView1.AllowPaging = false;
GridView1.DataBind();
string[] hiddenCols = { "", "Reject" };
StringBuilder columnbind = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
bool isHidden = true;
foreach (string str in hiddenCols)
{
if (GridView1.Columns[k].HeaderText == str)
{
isHidden = false;
break;
}
}
if (isHidden)
columnbind.Append(GridView1.Columns[k].HeaderText + ',');
}
columnbind.Append("\r\n");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
bool isHidden = true;
foreach (string str in hiddenCols)
{
if (GridView1.Columns[k].HeaderText == str)
{
isHidden = false;
break;
}
}
if (isHidden)
{
columnbind.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
}
columnbind.Append("\r\n");
}
Response.Output.Write(columnbind.ToString());
Response.Flush();
Response.End();
}
I have tow grid views master grid is gridpurchase and child grid is gvItems
I am trying to hide some columns in gvItems when exporting the grids to excel file.
i have tried the below code but it didn't work
Exporting code
protected void btnexcel_Click(object sender, EventArgs e)
{
gridpurchase.DataSource = po.GetPurchaseOrders();
gridpurchase.DataBind();
GridView gvItems = gridpurchase.FindControl("gvItems") as GridView;
gvItems.Columns[0].Visible = false;
gridpurchase.GridLines = GridLines.Both;
foreach (GridViewRow row in gridpurchase.Rows)
{
foreach (TableCell cell in row.Cells)
{
for (int i = cell.Controls.Count - 1; i >= 0; i--)
{
if (cell.Controls[i] is Image)
{
Image img = cell.Controls[i] as Image;
if (img.ImageUrl.Contains("plus.png") || img.ImageUrl.Contains("minus.png"))
{
cell.Controls.RemoveAt(i);
}
}
}
}
}
gridpurchase.Caption = "Purchase Orders Report";
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
curContext.Response.Clear();
curContext.Response.Buffer = true;
curContext.Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("PurchaseOrdersReport", System.Text.Encoding.UTF8) + ".xls");
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
gridpurchase.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
Grid-view
<asp:GridView ID="gridpurchase" OnRowCommand="gridpurchase_RowCommand" OnRowDataBound="gridpurchase_RowDataBound" DataKeyNames="RequisitionID" GridLines="None" runat="server" CssClass="table text-nowrap" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Preview">
<ItemTemplate>
<asp:Image ID="imgPlus" runat="server" AlternateText="" ImageUrl="img/plus.png" Style="cursor: pointer" />
<asp:Panel ID="pnlproducts" runat="server" Style="display: none">
<asp:GridView ID="gvItems" CssClass="table table-bordered" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="ItemName" HeaderText="Item Name" SortExpression="ItemName" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SupplierName" HeaderText="Supplier Name" SortExpression="SupplierName" />
<asp:BoundField DataField="PurchaseOrderCode" HeaderText="Purchase Order Code" SortExpression="PurchaseOrderCode" />
</Columns>
</asp:GridView>
According to your markup, there is a gvItems GridView inside of each row of gridpurchase. You can retrieve every child GridView in your main loop:
foreach (GridViewRow row in gridpurchase.Rows)
{
GridView gvItems = row.FindControl("gvItems") as GridView;
gvItems.Columns[0].Visible = false;
foreach (TableCell cell in row.Cells)
{
...
}
}
Change your foreach loop like this
gridpurchase.HeaderRow.Cells[0].Visible = false;
foreach (GridViewRow row in gridpurchase.Rows)
{
row.Cells[0].Visible = false;
}
This will remove the first column from your asp:GridView
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();
}
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.!
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 */
}